Bry*_*wis 21 chart.js chart.js2
我有一个条形图,我绘制了3条垂直线,每条线在顶部都有自己的标签.我希望这些标签位于y轴的顶部之上(在示例中位于30%线之上)但在图例下方.我无法弄清楚如何增加顶部图例和图表之间的空间,这样我可以让我的垂直线标签(15,24和33)偏离图表本身但在图例下方.有任何想法吗?
Glo*_*ogo 23
如果有人想知道为什么该afterFit解决方案在 Chart.js 3.3.0 中不起作用,那是因为该afterFit函数已从图例插件中删除。
如果你想通过利用该fit功能来完成这项工作,你可以尝试这个 hacky 解决方案/解决方法:
const plugin = {
beforeInit(chart) {
// Get a reference to the original fit function
const originalFit = chart.legend.fit;
// Override the fit function
chart.legend.fit = function fit() {
// Call the original function and bind scope in order to use `this` correctly inside it
originalFit.bind(chart.legend)();
// Change the height as suggested in other answers
this.height += 15;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这不是一个理想的解决方案,但在我们对这个图例填充提供本机支持之前,恐怕这已经是我们现在能做的最好的了。
Dor*_*ski 19
如果您想在所有图表中增加间距,可以在创建之前放置此代码:
Chart.Legend.prototype.afterFit = function() {
this.height = this.height + 50;
};
Run Code Online (Sandbox Code Playgroud)
当然,我不尝试,但我认为你可以改变它(或复制原始的Chart对象,以保持原始填充).
再见,
经过2天的研究,这对我有所帮助。
Chart.Legend.prototype.afterFit = function() {
this.height = this.height + 50;
};
Run Code Online (Sandbox Code Playgroud)
在 module.ts 文件中更新
如果您只想在应用中为某些图表应用图例下的填充:
ChartJS> = 2.1.0
Chart.plugins.register({
id: 'paddingBelowLegends',
beforeInit: function(chart, options) {
chart.legend.afterFit = function() {
this.height = this.height + 50;
};
}
});
// ----------------------------------
// disable the plugin only for charts
// where you DO NOT WANT the padding
// ----------------------------------
// for raw ChartJS use:
var chart = new Chart(ctx, {
config: {
plugins: {
paddingBelowLegends: false
}
}
});
// for angular-chartjs:
$scope.myChart.options.plugins = { paddingBelowLegends: false }
// then in template:
// <canvas class="chart ..." chart-options="myChart.options" ... />
Run Code Online (Sandbox Code Playgroud)
ChartJS> = 2.5.0
支持每个图表的特定插件,应该可以这样做:
var chart = new Chart(ctx, {
plugins: [{
beforeInit: function(chart, options) {
chart.legend.afterFit = function() {
this.height = this.height + 50;
};
}
}]
});
Run Code Online (Sandbox Code Playgroud)
小智 8
我正在使用react-chartjs-2(但这只是一个端口并使用相同的配置对象),我可以通过更改嵌套在图例配置上的标签配置来实现这一点:
chartOptions = {
legend: {
labels: {
padding: 50 -> this one.
}
},
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看属性描述: https: //www.chartjs.org/docs/latest/configuration/legend.html
希望能帮助到你。