前两篇文章介绍了在Python中使用wordcloud模块生成词云图,那么怎样在html中直接生成词云图呢?
下面介绍一种对小白特别友好的方式:d3.js(官网地址:https://d3js.org/)
需要准备的js:
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="d3.layout.cloud.js"></script>
d3.layout.cloud.js和示例代码都放在github中,有兴趣自取。
github地址:https://github.com/736755244/d3.js-
1、简单效果如下:
2、代码如下:
<!--html-->
<div id="container"></div>
<!--js-->
//获得数据
var frequency_list = [
{"text":"好看", "size":50},
{"text":"安利", "size":20},
{"text":"一定去看", "size":40},
{"text":"三刷啦", "size":30},
{"text":"超感人的", "size":19},
{"text":"上座率爆炸", "size":100},
{"text":"人满为患", "size":50},
{"text":"抢到票了", "size":70},
{"text":"特效炒鸡棒", "size":90},
{"text":"泪目", "size":120},
{"text":"真的好好看", "size":54},
{"text":"哈哈哈哈", "size":555},
{"text":"大家随意", "size":220},
{"text":"搞起来", "size":80},
{"text":"五排啊", "size":19},
{"text":"王者上机", "size":100}
]
//自定义一个线性非连贯比例尺来进行给不同大小的词赋颜色.
// var color = d3.scale.linear()
// .domain([0,1,2,3,4,5,6,10,15,20,100])
// .range(["#ddd", "#ccc", "#bbb", "#aaa", "#999", "#888", "#777", "#666", "#555", "#444", "#333", "#222"]);
var color = d3.scale.category20(); //直接使用d3的方法,产生20种类别的颜色
var layout = d3.layout.cloud()
.size([400, 300])
.words(frequency_list)
.rotate(0)
.fontSize(function(d) { return d.size; })
.on("end", draw);
layout.start();
function draw(words) {
d3.select("#container").append("svg")//根据id插入svg
.attr("width", layout.size()[0])//宽度
.attr("height", layout.size()[1])//高度
.attr("viewBox","0 0 600 350")//可见区域
.attr("style", "border: 1px solid black")//区域样式
.attr("preserveAspectRatio","xMaxYMax meet")
.attr("class", "wordcloud")
.append("g")
.attr("transform", "translate(200,100)")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("fill", function(d, i) { return color(i); })//颜色
.attr("transform", function(d) {//每个词条的偏移量
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });//内容
}
相关问题欢迎留言讨论!