如何在图表中以字符串形式获取x轴值?

问题描述 投票:0回答:1

我正在尝试使用chart.js绘制图形,其中y轴值为数字,x轴值为字符串。我已经给出了编写的代码,但是没有绘制字符串值。感谢您的帮助。

window.onload = function() {
  var dataPoints7 = [];

  var chart7 = new CanvasJS.Chart("chartContainer7", {
    animationEnabled: true,
    theme: "light2",
    title: {
      text: "Cases in States"
    },
    axisY: {
      title: "Cases",
      titleFontSize: 24
    },
    data: [{
      type: "line",
      yValueFormatString: "#,### Cases",
      dataPoints: dataPoints7
    }]
  });
  fetch("https://api.covid19india.org/data.json", {
      "method": "GET"
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      for (var i = 1; i < data.statewise.length; i++) {
        dataPoints7.push({
          x: data.statewise[i].state,
          y: parseInt(data.statewise[i].confirmed)
        });
      }
      chart7.render();
    });
}
<!DOCTYPE html>
<html lang="en">

<div id="chartContainer7" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

</html>
javascript html chart.js
1个回答
0
投票

对于您的情况,您应该提供label 属性而不是x值,并且我相信您应该为此使用柱状图。

您可能会看到一些标签没有显示出来。您可以设置角度或增加图表的宽度以使其可见。

尝试运行此代码段

window.onload = function() {
  var dataPoints7 = [];

  var chart7 = new CanvasJS.Chart("chartContainer7", {
    animationEnabled: true,
    theme: "light2",
    title: {
      text: "Cases in States"
    },
    axisY: {
      title: "Cases",
      titleFontSize: 24
    },
    axisX: {
      labelAngle: 180
    },
    data: [{
      type: "line",
      yValueFormatString: "#,### Cases",
      dataPoints: dataPoints7
    }]
  });
  fetch("https://api.covid19india.org/data.json", {
      "method": "GET"
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      for (var i = 1; i < data.statewise.length; i++) {
        dataPoints7.push({
          label: data.statewise[i].state,
          y: parseInt(data.statewise[i].confirmed)
        });
      }
      chart7.render();
    });

}
<!DOCTYPE html>
<html lang="en">

<div id="chartContainer7" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

</html>
© www.soinside.com 2019 - 2024. All rights reserved.