chart.js - 使用 ChartJS 绘制带有平均线的堆叠水平条形图
问题描述
我正在尝试使用 ChartJS 库创建一个堆叠的水平条形图,每个条上都有一条平均线。我试了几次,在网上搜索,但没有找到满意的答案。感谢您的帮助。谢谢。
例子:
.
在此示例中,每个柱上的红线表示其组的平均值。
要创建堆叠水平条形图,请参阅 https://jsfiddle.net/lamtn862004/9wm1krqf/10/。
var data = {
labels: ["January", "February", "March"],
datasets: [
{
label: "Dogs",
backgroundColor: "rgba(237, 192, 169)",
data: [20, 10, 25],
stack: 1,
xAxisID: 'x-axis-0',
yAxisID: 'y-axis-0'
},
{
label: "Cats",
backgroundColor: "rgba(253, 234, 175)",
data: [70, 85, 65],
stack: 1,
xAxisID: 'x-axis-0',
yAxisID: 'y-axis-0'
},
{
label: "Birds",
backgroundColor: "rgba(179, 211, 200)",
data: [10, 5, 10],
stack: 1,
xAxisID: 'x-axis-0',
yAxisID: 'y-axis-0'
},
]
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, {
type: 'groupableHBar',
data: data,
options: {
scales: {
yAxes: [{
stacked: true,
type: 'category',
id: 'y-axis-0'
}],
xAxes: [{
stacked: true,
type: 'linear',
ticks: {
beginAtZero:true
},
gridLines: {
display: false,
drawTicks: true,
},
id: 'x-axis-0'
},
{
stacked: true,
position: 'top',
type: 'linear',
ticks: {
beginAtZero:true
},
id: 'x-axis-1',
gridLines: {
display: true,
drawTicks: true,
},
display: false
}]
}
}
});
现在,我想将平均线添加到每个条形(如图所示)。
另外,您知道其他使用开源库的解决方案吗?
解决方案
可以使用连接到单独轴的浮动条来绘制线条y2
。为此,您需要dataset
按如下方式添加另一个(我不完全了解您要显示的值,因此我随机选择了40
,65
和55
):
{
label: "Lines",
backgroundColor: "rgb(255, 0, 0)",
data: [40, 65, 55].map(v => [v - 0.3, v + 0.3]),
yAxisID: 'y2',
order: -1
}
此外,您必须定义一个新scales
option
的,如下所示:
y2: {
display: false
}
请查看您修改后的可运行代码,看看它是如何工作的。
var data = {
labels: ["January", "February", "March"],
datasets: [{
label: "Dogs",
backgroundColor: "rgba(237, 192, 169)",
data: [20, 10, 25]
},
{
label: "Cats",
backgroundColor: "rgba(253, 234, 175)",
data: [70, 85, 65]
},
{
label: "Birds",
backgroundColor: "rgba(179, 211, 200)",
data: [10, 5, 10]
},
{
label: "Lines",
backgroundColor: "rgb(255, 0, 0)",
data: [40, 65, 55].map(v => [v - 0.3, v + 0.3]),
yAxisID: 'y2',
order: -1
}
]
};
new Chart('myChart', {
type: 'bar',
data: data,
options: {
indexAxis: 'y',
plugins: {
legend: {
display: false
}
},
scales: {
y: {
stacked: true,
grid: {
display: false
}
},
y2: {
display: false
},
x: {
stacked: true,
beginAtZero: true,
grid: {
display: false
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>
推荐阅读
- amazon-web-services - AWS sending logs from cloudwatch to elasticsearch but there is one less in elasticsearch without any errors
- php - PHP admin mysql 数据库的大小从 120 mb 缩小到 15 字节
- angular - Angular HttpHeaders 未设置值
- android - 应用程序运行但: - E/MediaPlayer:应该已经设置了字幕控制器
- xamarin - Xamarin/iOS/Android - 聚焦文本字段时显示其他元素
- c++ - 匿名联合的默认构造函数和析构函数的未定义行为?
- r - 有没有人尝试过使用带有游侠回归模型的 iml 包中的 Shapley 函数?
- angular - 将角度组件分配给按钮事件
- mysql - MySQL 表正在使用但不存在
- javascript - React + Electron webview标签预加载js不起作用