[英]Using JSON data to create treemap using google charts or 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数据绘制一个树形图,如下所示:
根据不同应用程序的计数值绘制树形图。 国家和时期可以忽略。
我找到了本文档“ 填充数据”,但问题是DataTable必须采用与我的DataTable不太相似的特定格式。 请提出如何使用d3.js或Google图表进行建议?
终于,我找到了路。
有两种方法可以做到这一点:
我用第一种方法做到了。
// 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.