javascript - 使用 JSON 数据使用谷歌图表或 d3.js 创建树状图
问题描述
我的一部分 JSON 数据如下。
[
{
"App": "app1",
"count": 8,
"country": "FR",
"period": "2018"
},
{
"App": "app2",
"count": 7,
"country": "FR",
"period": "2018"
},
{
"App": "app3",
"count": 12,
"country": "FR",
"period": "2018"
},
{
"App": "app4",
"count": 2,
"country": "FR",
"period": "2018"
},
{
"App": "app5",
"count": 25,
"country": "FR",
"period": "2018"
},
{
"App": "app6",
"count": 49,
"country": "FR",
"period": "2018"
},
{
"App": "app7",
"count": 5,
"country": "FR",
"period": "2018"
},
{
"App": "app8",
"count": 189,
"country": "FR",
"period": "2018"
}
]
.
我想为这个 JSON 数据绘制一个树形图,如下所示:
树状图是根据不同应用程序的计数值绘制的。国家和时期可以忽略。
我找到了这个文档填充数据但问题是数据表必须采用与我的数据表不太相似的特定格式。请建议我如何使用 d3.js 或谷歌图表来做到这一点?
解决方案
最后,我找到了方法。
有两种可能的方法来做到这一点:
我用第一种方法做到了。
// treemap.js
var objarr = [
{
"App": "app1",
"count": 8,
"country": "FR",
"period": "2018"
},
{
"App": "app2",
"count": 7,
"country": "FR",
"period": "2018"
},
{
"App": "app3",
"count": 12,
"country": "FR",
"period": "2018"
},
{
"App": "app4",
"count": 2,
"country": "FR",
"period": "2018"
},
{
"App": "app5",
"count": 25,
"country": "FR",
"period": "2018"
},
{
"App": "app6",
"count": 49,
"country": "FR",
"period": "2018"
},
{
"App": "app7",
"count": 5,
"country": "FR",
"period": "2018"
},
{
"App": "app8",
"count": 189,
"country": "FR",
"period": "2018"
}
]
var arrArr = [['app','parent', 'count'],['app', null, 0]]
var n = objarr.length;
for ( i = 0; i < n; i++){
arrArr[i+2] = [objarr[i].App, 'app', objarr[i].count]
}
google.charts.load('current', {'packages':['treemap']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(arrArr);
tree = new google.visualization.TreeMap(document.getElementById('chart_div'));
tree.draw(data, {
minColor: '#f00',
midColor: '#ddd',
maxColor: '#0d0',
headerHeight: 15,
fontColor: 'black',
showScale: true
});
}
并在您的 index.html 中使用此脚本。
// index.html
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="try.js">
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
推荐阅读
- xml - 尝试将 StaxSource 转换为 StreamResult 时,Xml Transformer 给我一个错误
- c# - 在绑定列表中查找对象索引?
- jquery - 是否可以在 jQuery 中自动将类添加到大写字母?
- flutter - 小部件列表未显示在屏幕上
- c++ - 当 StringSink 使用的 String 超出范围时程序崩溃
- javascript - 使用 React Native 将 props 从子函数传递到父函数
- typescript - 如何键入更改函数参数的对象?
- android - 在不更改模态本身的情况下更改模态表中的数据
- flutter - Dart 检查 num 是 Double 或 Integer
- rest - 基于openapi.yaml搭建rest mock服务器的方法