"Inline" ChartJS 中的标签
"Inline" labels in ChartJS
是否可以在 ChartJS 的水平条之间呈现带有 "inline" 标签的图表?
您可以为此使用 chartjs-plugin-datalabels
,这在显示任何类型图表的数据标签时非常有用,并且可高度自定义。
Note that this requires Chart.js 2.7.0 or later.
通过将其包含在图表 options
的 plugins
键下来使用它,如下面的解决方案所示。
解决方案#1。
下面的配置将在每个栏的 top center
上显示您的标签。参见 working example。
var options = {
plugins: {
datalabels: {
// use the formatter function to customize the labels displayed
formatter: function(value, context) {
return context.chart.data.labels[context.dataIndex];
},
align: "top",
anchor: "center",
offset: 25,
padding: -2,
clip: true,
font: {
size: "16",
weight: "bold"
}
}
}
};
但是,这与您提供的屏幕截图并不完全相同,
解决方案#2。
这是我可以建议的一种解决方法来复制您想要的确切行为。
anchor: 'start'
and align: -60
: that will bring your data label on top, left aligned
make your chart start at zero by setting scale.ticks.beginAtZero
to true
offset: 25
: distance (in pixels) to pull the label away from the anchor point
padding: function() {}
: use a scriptable option to dynamically compute the left padding based on the label approximate size since adding a specific padding will only work if your labels have the same width that doesn't change which is not this case
有关配置的详细概述,请参阅 working example。
This solution will work but it's definitely not ideal since the
position of these labels may change depending on the label size, bar
thickness, and the size of the chart.
是否可以在 ChartJS 的水平条之间呈现带有 "inline" 标签的图表?
您可以为此使用 chartjs-plugin-datalabels
,这在显示任何类型图表的数据标签时非常有用,并且可高度自定义。
Note that this requires Chart.js 2.7.0 or later.
通过将其包含在图表 options
的 plugins
键下来使用它,如下面的解决方案所示。
解决方案#1。
下面的配置将在每个栏的 top center
上显示您的标签。参见 working example。
var options = {
plugins: {
datalabels: {
// use the formatter function to customize the labels displayed
formatter: function(value, context) {
return context.chart.data.labels[context.dataIndex];
},
align: "top",
anchor: "center",
offset: 25,
padding: -2,
clip: true,
font: {
size: "16",
weight: "bold"
}
}
}
};
但是,这与您提供的屏幕截图并不完全相同,
解决方案#2。
这是我可以建议的一种解决方法来复制您想要的确切行为。
anchor: 'start'
andalign: -60
: that will bring your data label on top, left alignedmake your chart start at zero by setting
scale.ticks.beginAtZero
totrue
offset: 25
: distance (in pixels) to pull the label away from the anchor point
padding: function() {}
: use a scriptable option to dynamically compute the left padding based on the label approximate size since adding a specific padding will only work if your labels have the same width that doesn't change which is not this case
有关配置的详细概述,请参阅 working example。
This solution will work but it's definitely not ideal since the position of these labels may change depending on the label size, bar thickness, and the size of the chart.