用echart绘制词云的详细步骤和详细代码
时间: 2024-05-14 22:16:31 浏览: 161
Echarts 是一个基于 JavaScript 的开源可视化库,提供了丰富的图表类型和交互功能。Echarts 中也提供了词云图的绘制功能。下面是使用 Echarts 绘制词云的详细步骤和代码。
步骤:
1. 引入 Echarts 库和词云插件
```html
<script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts-wordcloud/dist/echarts-wordcloud.min.js"></script>
```
2. 创建一个 DOM 元素作为图表容器
```html
<div id="wordcloud" style="width: 600px;height:400px;"></div>
```
3. 在 JavaScript 中定义词云的数据和配置项
```javascript
var data = [
{
name: 'JavaScript',
value: 10000
},
{
name: 'Java',
value: 6181
},
{
name: 'Python',
value: 4386
},
{
name: 'PHP',
value: 4055
},
{
name: 'C++',
value: 2467
},
{
name: 'C#',
value: 2244
},
{
name: 'HTML',
value: 1898
},
{
name: 'CSS',
value: 1484
},
{
name: 'TypeScript',
value: 1112
},
{
name: 'Ruby',
value: 965
}
];
var option = {
series: [{
type: 'wordCloud',
shape: 'circle',
left: 'center',
top: 'center',
width: '80%',
height: '80%',
textStyle: {
fontFamily: 'sans-serif',
fontWeight: 'bold',
color: function () {
return 'rgb(' + [
Math.round(Math.random() * 160),
Math.round(Math.random() * 160),
Math.round(Math.random() * 160)
].join(',') + ')';
}
},
emphasis: {
focus: 'self',
textStyle: {
shadowBlur: 10,
shadowColor: '#333'
}
},
data: data
}]
};
```
4. 创建词云图表并绑定数据和配置项
```javascript
var chart = echarts.init(document.getElementById('wordcloud'));
chart.setOption(option);
```
完整代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>使用 Echarts 绘制词云</title>
<script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts-wordcloud/dist/echarts-wordcloud.min.js"></script>
</head>
<body>
<div id="wordcloud" style="width: 600px;height:400px;"></div>
<script>
var data = [
{
name: 'JavaScript',
value: 10000
},
{
name: 'Java',
value: 6181
},
{
name: 'Python',
value: 4386
},
{
name: 'PHP',
value: 4055
},
{
name: 'C++',
value: 2467
},
{
name: 'C#',
value: 2244
},
{
name: 'HTML',
value: 1898
},
{
name: 'CSS',
value: 1484
},
{
name: 'TypeScript',
value: 1112
},
{
name: 'Ruby',
value: 965
}
];
var option = {
series: [{
type: 'wordCloud',
shape: 'circle',
left: 'center',
top: 'center',
width: '80%',
height: '80%',
textStyle: {
fontFamily: 'sans-serif',
fontWeight: 'bold',
color: function () {
return 'rgb(' + [
Math.round(Math.random() * 160),
Math.round(Math.random() * 160),
Math.round(Math.random() * 160)
].join(',') + ')';
}
},
emphasis: {
focus: 'self',
textStyle: {
shadowBlur: 10,
shadowColor: '#333'
}
},
data: data
}]
};
var chart = echarts.init(document.getElementById('wordcloud'));
chart.setOption(option);
</script>
</body>
</html>
```
阅读全文