我正在尝试使用Chart.js在多轴条形图中绘制烧瓶中的一对列表。我可以绘制图表,但无法显示图例

时间:2019-03-19 12:22:49

标签: javascript jquery chart.js

我一直在尝试使用chart.js在html页面上绘制使用json返回的一对列表。我已经能够使用chart.js绘制数据,但无法创建图例。下面给出了chart.js函数的代码-

function addData(chartID, labels, data) {
      Chart.defaults.scale.ticks.beginAtZero = true;
      Chart.defaults.global.responsive = true;
      Chart.defaults.global.maintainAspectRatio = true;

      var ctx = document.getElementById(chartID).getContext('2d');
      var newChartData = {};

      newChartData.type = "bar";
      newChartData.data = {};
      newChartData.data.labels = [];
      newChartData.data.datasets = [];
      newChartData.options = {};
      newChartData.options.legend = {
        enabled: true,
        display: true,
      };
      newChartData.options.legend.labels = {
        fontColor: 'black',
        fontSize: 18
      }

      data.labels.forEach((label) => {
        newChartData.data.labels.push(label);
      });
      data.datasets.forEach((dataset) => {
        newChartData.data.datasets.push(dataset);
      });
      console.log(JSON.stringify(newChartData, null, 2));
      console.log(newChartData);

      var chart_plot = new Chart(ctx, newChartData);
      chart_plot.update();
    }




    var lab = ['TV', 'Press', 'Airport OOH', 'Search', 'Facebook', 'Twitter', 'Display', 'Affiliates'];

    var dataFirst = {
      label: "% Change in Spends",
      data: [20, 15, 60, 60, 65, 30, 70],
      backgroundColor: [
        'rgba(219, 0, 17, 0.8)',
        'rgba(219, 0, 17, 0.8)',
        'rgba(219, 0, 17, 0.8)',
        'rgba(219, 0, 17, 0.8)',
        'rgba(219, 0, 17, 0.8)',
        'rgba(219, 0, 17, 0.8)',
        'rgba(219, 0, 17, 0.8)'
      ],
      // Set More Options
    };

    var dataSecond = {
      label: "% Change in Applications",
      data: [0, 59, 75, 20, 20, 55, 40],
      backgroundColor: [
        'rgba(117, 117, 117, 0.8)',
        'rgba(117, 117, 117, 0.8)',
        'rgba(117, 117, 117, 0.8)',
        'rgba(117, 117, 117, 0.8)',
        'rgba(117, 117, 117, 0.8)',
        'rgba(117, 117, 117, 0.8)',
        'rgba(117, 117, 117, 0.8)'
      ],
      // Set More Options
    };

    var speedData = {
      labels: ['TV', 'Press', 'Airport OOH', 'Search', 'Facebook', 'Twitter', 'Display', 'Affiliates'],
      datasets: [dataFirst, dataSecond]
    };

addData('chart_plot', lab, speedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<html>
<body>
<canvas id="chart_plot" width="400" height="400"></canvas>
</body>
</html>

我尝试做的事情-

  1. 尝试过“ Chart.defaults.global.legend = true;”
  2. 尝试过“ newChartData.options.legend = {enabled:true,display:true,}; newChartData.options.legend.labels = {fontColor:'black',fontSize:18}“

我是JS,Jquery和chart.js的新手。我确定我在这里丢失了一些关键的代码。如果有人能告诉我我要去哪里错了,我将不胜感激。

0 个答案:

没有答案