首页 > 解决方案 > 使用 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 或谷歌图表来做到这一点?

标签: javascriptangularjsjsond3.jsgoogle-visualization

解决方案


最后,我找到了方法。
有两种可能的方法来做到这一点:

  • 将您的 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>

推荐阅读