首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >堆叠条形图上的ChartJS注释线

堆叠条形图上的ChartJS注释线
EN

Stack Overflow用户
提问于 2022-07-22 00:48:11
回答 1查看 290关注 0票数 0

我无法让注释行在堆叠条形图上工作。

示例JS:https://jsfiddle.net/cledwyn/rd5q6Lsz/10/

我有https://www.chartjs.org/chartjs-plugin-annotation/latest/samples/charts/bar.html的标准注释

代码语言:javascript
运行
复制
const annotation2 = {
  type: 'line',
  scaleID: 'x',
  borderWidth: 3,
  borderColor: 'black',
  value: 8,
  label: {
    rotation: 'auto',
    position: 'start',
    backgroundColor: 'black',
    content: 'Line at x=Label 5',
    enabled: true
  }
};

但当我把条形图叠起来的时候

代码语言:javascript
运行
复制
      scales: {
        xAxes: { stacked: true },
        yAxes: { stacked: true }
      },

然后注释行就从图表的一个角落转到另一个角落。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-22 05:37:16

运行JSFiddle时,您可以在控制台上看到以下警告。

代码语言:javascript
运行
复制
"No scale found with id 'x' for annotation 'annotation2'"

因此,将scales.xAxes更改为scales.x应该可以解决部分问题。

代码语言:javascript
运行
复制
scales: {
  x: { stacked: true },
  y: { stacked: true }
}

您还必须向data.labels添加缺少的标签并调整annotation2.value

请在下面看一看你的修正代码,看看它是如何工作的。

代码语言:javascript
运行
复制
const labels = ['Label 1', 'Label 2', 'Label 3',  'Label 4', 'Label 5'];
const data = {
  labels: labels,
  datasets: [{
    label: 'one',
    data: [14, 21, 4, 5, 7],
    backgroundColor: 'rgb(255, 99, 132)'
  }, {
    label: 'two',
    data: [1, 3, 2, 4, 5],
    backgroundColor: 'rgb(255, 199, 132)'
  }, {
    label: 'three',
    data: [7, 1, 9, 6, 7],
    backgroundColor: 'rgb(255, 99, 32)'
  }]
};

const annotation2 = {
  type: 'line',
  scaleID: 'x',
  borderWidth: 3,
  borderColor: 'black',
  value: 4,
  label: {
    rotation: 'auto',
    position: 'start',
    backgroundColor: 'black',
    content: 'Line at x=Label 5',
    enabled: true
  }
};

const config = {
  type: 'bar',
  data: data,
  options: {
    plugins: {
      annotation: {
        annotations: {
          annotation2,
        }
      }
    },
    scales: {
      x: {
        stacked: true
      },
      y: {
        stacked: true
      }
    },
  },
};

const chart = new Chart('chart', config);
代码语言:javascript
运行
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.4.0/chartjs-plugin-annotation.min.js"></script>
<canvas id="chart" height="110"></canvas>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73074010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档