繁体   English   中英

使用JSON数据使用Google图表或d3.js创建树形图

[英]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图表进行建议?

终于,我找到了路。
有两种方法可以做到这一点:

  • 将您的JSON数据转换为数组数组,然后单击此链接

  • 使用Angular-google-chart。 为此,您必须按照此处所述将数据转换为DataTable格式。 之后,您可以点击此链接

我用第一种方法做到了。

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM