如何使用具有自定义数据配置的 amcharts 创建实心仪表图?

How to create a solid gauge chart using amcharts with custom data configuration?

我有一个 AmCharts 实心仪表图表示例,我想使用“类别”和“大小”文本框中的值来呈现它。例如,文本区域将有此 JSON 数据,

[
{
      "Country":"Malaysia",
      "Size":260,
      "State":"Selangor",
      "Population":450
   },
   {
      "Country":"England",
      "Size":140,
      "State":"Liverpool",
      "Population":100
   },
   {
      "Country":"China",
      "Size":250,
      "State":"Beijing",
      "Population":200
   },
   {
      "Country":"South Korea",
      "Size":360,
      "State":"Seoul",
      "Population":300
   }
]

然后我将 Category 设置为 Country ,因此它会加载 4 个轴和 4 个标签。

然后我将 Size 设置为 Population ,因此它加载 endValue(startValue 从 0 开始对吗?)就是那个。百分比来自 maxValue * 1.2。

我的主要问题是,如何使用带有自定义数据配置的 AmCharts 渲染仪表图? dataProvider 在这里似乎不像在串行图表中那样工作。

Codepen link : https://codepen.io/ariff20/pen/WaKJRV

进一步阐述我的评论 - 由于仪表图表中不存在 dataProvider,您可以重新映射数据并在配置中创建适当的 properties/arrays,而不是尝试在你的代码笔。例如,您的乐队可以像这样生成:

  var colors = ["#84b761", "#fdd400", "#cc4748", "#67b7dc"]; //assuming 4 bands/colors - adjust as needed
  var bands = mappedData.reduce(function(acc, d, idx) {
    acc.push({
      color: "#eee",
      startValue: 0,
      endValue: d.target,
      radius: 100 - 20 * idx + "%",
      innerRadius: 85 - 20 * idx + "%"
    });
    acc.push({
      color: colors[idx],
      startValue: 0,
      endValue: d.value,
      radius: 100 - 20 * idx + "%",
      innerRadius: 85 - 20 * idx + "%",
      balloonText: parseFloat(d.value / d.target * 100).toFixed(2)
    });
    return acc;
  }, []);

可以用类似的方式生成标签:

  var labels = mappedData.map(function(d, idx) {
    return {
      text: d.name,
      x: "49%",
      y: 6 + 9 * idx + "%",
      size: 15,
      bold: true,
      color: colors[idx],
      align: "right"
    };
  });

生成后,只需填写您的设置模板中的空白并将其传递到您的 makeChart 调用中,首先清除所有以前的实例:

var chart; //global ref to clear the chart
function changeData() {
  // ... omitted
  var setting = {
    type: "gauge",
    theme: "light",
    axes: [
      {
        axisAlpha: 1,
        tickAlpha: 1,
        labelsEnabled: true,
        startValue: 0,
        endValue: Math.max.apply(
          Math,
          mappedData.map(function(o) {
            return o.target;
          })
        ),
        startAngle: 0,
        endAngle: 270,
        bands: bands
      }
    ],
    allLabels: labels,
    export: {
      enabled: true
    }
  };
  if (chart) {
    chart.clear();
    chart = null;
  }
  chart = AmCharts.makeChart("chartdiv", setting);
}

Demo