wordcloud 设置颜色怎么设置颜色

【T】wordcloud--标签云制作
该博文已整理到新地址:http://qinqianshan.com/wordcloud-tag-cloud-card/
标签云是文字的视觉化描述。通常以字号和颜色来映射文字的相关属性。比如把词频映射到字号,把词性映射到颜色等。要想制作具有视觉冲击的标签云,要把重点放在字体和颜色的选择上。已经有很多工具可以制作标签云,最有名的莫过于wordpress,遗憾的是wordpress不支持中文的标签云制作,本文主要通过两个实例演示基于的。
example(wordcloud)
函数——用于制作常规的词云图
wordcloud(words,freq,scale=c(4,.5),min.freq=3,max.words=Inf,random.order=TRUE,
random.color=FALSE,
rot.per=.1,colors="black",ordered.colors=FALSE,use.r.layout=FALSE,...)
2.参数介绍:
(1)words——关键词列表
(2)freq——关键词对应的词频列表
(3)scale——字号列表。c(最大字号,
(4)min.freq——最小限制频数。低于此频数的关键词将不会被显示。
(5)max.words——限制词云图上关键词的数量。最后出现在词云图上的关键词数量不超过此限制。
(6)random.order——控制关键词在图上的排列顺序。T:关键词随机排列;F:关键词按频数从图中心位置往外降序排列,即频数大的词出现在中心位置。
(7)random.color——控制关键词的字体颜色。T:字体颜色随机分配;F:根据频数分配字体颜色。
(8)rot.per——控制关键词摆放角度。T:水平摆放;F:旋转90度。
(9)colors——字体颜色列表
(10)ordered.colors——控制字体颜色使用顺序。T:按照指定的顺序给出每个关键词字体颜色,(似乎是要求颜色列表中每个颜色一一对应关键词列表);F:任意给出字体颜色。
(11)use.r.layout=T;F
具体使用案例
1.安装程序包
2.加载程序包
3.给出字体颜色
自己指定字体颜色
colors=c('red','blue','green','yellow','purple')
或者使用R颜色程序包中现成的主题模板
4.读取原数据
原始数据放在
了test.csv文件里,分2列:关键词、频数。且第一行为列标题:words、freq
data=read.csv("c:/test.csv")
5.执行函数
(data$words,data$freq,scale=c(3,0.3),min.freq=-Inf,max.words=Inf,colors=colors,random.order=F,random.color=F,ordered.colors=F)
参考资料:
感谢QQ好友分享的代码解释
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。没有更多推荐了,
不良信息举报
举报内容:
wordcloud用来制作词云
举报原因:
原文地址:
原因补充:
最多只允许输入30个字
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!没有更多推荐了,
不良信息举报
举报内容:
Python词云 wordcloud 十五分钟入门与进阶
举报原因:
原文地址:
原因补充:
最多只允许输入30个字
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!没有更多推荐了,
不良信息举报
举报内容:
Wordcloud词云教程
举报原因:
原文地址:
原因补充:
最多只允许输入30个字
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!Python词云 wordcloud 十五分钟入门与进阶这篇文章是我上个月发表在CSDN的博客,虽然被推到了首页,然而访问量依旧惨不忍睹=- =,不过好在质量还不错,所以再发到知乎来凑凑热闹我的博客中有完整的系列内容(附带代码),文章最后有传送门:整体简介基于的词云生成类库,很好用,而且功能强大.博主个人比较推荐 github: 官方地址: 写这篇文章花费一个半小时,阅读需要十五分钟,读完本篇文章后您将能上手wordcloud中文词云与其他要点,我将会在下一篇文章中介绍快速生成词云rom wordcloud import WordCloud
f = open(u'txt/AliceEN.txt','r').read()
wordcloud = WordCloud(background_color="white",width=1000, height=860, margin=2).generate(f)
# width,height,margin可以设置图片属性
# generate 可以对全部文本进行自动分词,但是他对中文支持不好,对中文的分词处理请看我的下一篇文章
#wordcloud = WordCloud(font_path = r'D:\Fonts\simkai.ttf').generate(f)
# 你可以通过font_path参数来设置字体集
#background_color参数为设置背景颜色,默认颜色为黑色
import matplotlib.pyplot as plt
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
wordcloud.to_file('test.png')
# 保存图片,但是在第三模块的例子中 图片大小将会按照 mask 保存
自定义字体颜色这段代码主要来自wordcloud的github,你可以在github下载该例子#!/usr/bin/env python
Colored by Group Example
========================
Generating a word cloud that assigns colors to words based on
a predefined mapping from colors to words
from wordcloud import (WordCloud, get_single_color_func)
import matplotlib.pyplot as plt
class SimpleGroupedColorFunc(object):
"""Create a color function object which assigns EXACT colors
to certain words based on the color to words mapping
Parameters
----------
color_to_words : dict(str -& list(str))
A dictionary that maps a color to the list of words.
default_color : str
Color that will be assigned to a word that's not a member
of any value from color_to_words.
def __init__(self, color_to_words, default_color):
self.word_to_color = {word: color
for (color, words) in color_to_words.items()
for word in words}
self.default_color = default_color
def __call__(self, word, **kwargs):
return self.word_to_color.get(word, self.default_color)
class GroupedColorFunc(object):
"""Create a color function object which assigns DIFFERENT SHADES of
specified colors to certain words based on the color to words mapping.
Uses wordcloud.get_single_color_func
Parameters
----------
color_to_words : dict(str -& list(str))
A dictionary that maps a color to the list of words.
default_color : str
Color that will be assigned to a word that's not a member
of any value from color_to_words.
def __init__(self, color_to_words, default_color):
self.color_func_to_words = [
(get_single_color_func(color), set(words))
for (color, words) in color_to_words.items()]
self.default_color_func = get_single_color_func(default_color)
def get_color_func(self, word):
"""Returns a single_color_func associated with the word"""
color_func = next(
color_func for (color_func, words) in self.color_func_to_words
if word in words)
except StopIteration:
color_func = self.default_color_func
return color_func
def __call__(self, word, **kwargs):
return self.get_color_func(word)(word, **kwargs)
text = """The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""
# Since the text is small collocations are turned off and text is lower-cased
wc = WordCloud(collocations=False).generate(text.lower())
# 自定义所有单词的颜色
color_to_words = {
# words below will be colored with a green single color function
'#00ff00': ['beautiful', 'explicit', 'simple', 'sparse',
'readability', 'rules', 'practicality',
'explicitly', 'one', 'now', 'easy', 'obvious', 'better'],
# will be colored with a red single color function
'red': ['ugly', 'implicit', 'complex', 'complicated', 'nested',
'dense', 'special', 'errors', 'silently', 'ambiguity',
'guess', 'hard']
# Words that are not in any of the color_to_words values
# will be colored with a grey single color function
default_color = 'grey'
# Create a color function with single tone
# grouped_color_func = SimpleGroupedColorFunc(color_to_words, default_color)
# Create a color function with multiple tones
grouped_color_func = GroupedColorFunc(color_to_words, default_color)
# Apply our color function
# 如果你也可以将color_func的参数设置为图片,详细的说明请看 下一部分
wc.recolor(color_func=grouped_color_func)
plt.figure()
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()
利用背景图片生成词云,设置停用词词集该段代码主要来自于wordcloud的github,你同样可以在github下载该例子以及原图片与效果图#!/usr/bin/env python
Image-colored wordcloud
=======================
You can color a word-cloud by using an image-based coloring strategy
implemented in ImageColorGenerator. It uses the average color of the region
occupied by the word in a source image. You can combine this with masking -
pure-white will be interpreted as 'don't occupy' by the WordCloud object when
passed as mask.
If you want white as a legal color, you can just pass a different image to
"mask", but make sure the image shapes line up.
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
d = path.dirname(__file__)
# Read the whole text.
text = open(path.join(d, 'alice.txt')).read()
# read the mask / color image taken from
# http://jirkavinse.deviantart.com/art/quot-Real-Life-quot-Alice-
alice_coloring = np.array(Image.open(path.join(d, "alice_color.png")))
# 设置停用词
stopwords = set(STOPWORDS)
stopwords.add("said")
# 你可以通过 mask 参数 来设置词云形状
wc = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,
stopwords=stopwords, max_font_size=40, random_state=42)
# generate word cloud
wc.generate(text)
# create coloring from image
image_colors = ImageColorGenerator(alice_coloring)
# 在只设置mask的情况下,你将会得到一个拥有图片形状的词云
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.figure()
# recolor wordcloud and show
# we could also give color_func=image_colors directly in the constructor
# 我们还可以直接在构造函数中直接给颜色
# 通过这种方式词云将会按照给定的图片颜色布局生成字体颜色策略
plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
plt.axis("off")
plt.figure()
plt.imshow(alice_coloring, cmap=plt.cm.gray, interpolation="bilinear")
plt.axis("off")
plt.show()
展示效果如下: 传送门9427 条评论分享收藏

我要回帖

更多关于 wordcloud 的文章

 

随机推荐