Chart.js - 增加图例和图表之间的间距间距、图表、图例、Chart

2023-09-07 11:20:28 作者:谎唁丶縂昰那麼的动听

我有一个条形图,我在其中绘制了 3 条垂直线,每条线的顶部都有自己的标签.我希望这些标签高于 y 轴的顶部(在示例中高于 30% 线)但低于图例.我不知道如何增加顶部图例和图表之间的空间,以便我可以让我的垂直线标签(15、24 和 33)脱离图表本身但低于图例.有什么想法吗?

I have a bar chart where I have drawn 3 vertical lines, each with it's own label at the top. I would like those labels to be above the top of the y-axis (above the 30% line in the example) but below the legend. I can't figure out how to increase the space between the top legend and the chart such that I can have my vertical line labels (15, 24 & 33) be off of the chart itself but below the legend. Any ideas?

推荐答案

不幸的是,由于没有配置选项来处理这个问题,唯一可以达到预期结果的方法是扩展 Chart.Legend 并实现 afterFit() 回调.

Unfortunately, since there is no config option to handle this the only way you can achieve the desired result is to extend Chart.Legend and implement the afterFit() callback.

这里有一个快速 codepen 展示如何做到这一点.要更改间距,只需更改第 9 行中的值(当前设置为 50).此外,这当然只适用于顶部的图例.希望该示例足够清晰,以便您在想将图例移至其他位置时进行修改.

Here is a quick codepen showing how to do just that. To change the spacing, just change the value in line 9 (currently set to 50). Also, this of course only works with the legend at the top. Hopefully, the example is clear enough for you to modify in case you want to move your legend elsewhere.