【问题标题】:Using JSON data to create treemap using google charts or d3.js使用 JSON 数据使用谷歌图表或 d3.js 创建树状图
【发布时间】:2018-11-21 17:33:52
【问题描述】:

我的一部分 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 数据绘制一个树形图,看起来像这样:

树状图是根据不同应用的计数值绘制的。国家和时期可以忽略。

我找到了此文档Populating Data 但问题是 DataTable 必须采用与我的 DataTable 不太相似的特定格式。请建议我如何使用 d3.js 或 Google 图表来做到这一点?

【问题讨论】:

  • 您可以执行类似于this answer 的操作,其中问题与您提供的示例相同...

标签: javascript angularjs json d3.js google-visualization


【解决方案1】:

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

  • 将您的 JSON 数据转换为数组数组,然后按照 link 操作。

  • 使用 Angular-google-chart。为此,您必须将数据转换为 DataTable 格式,如here 所述。之后,你可以关注这个link

我是用第一种方法做的。

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

【讨论】:

    猜你喜欢
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    相关资源
    最近更新 更多