gpt4 book ai didi

javascript - chart.js:在饼图外显示标签

转载 作者:可可西里 更新时间:2023-11-01 01:54:21 24 4
gpt4 key购买 nike

chart.js 2.6.0

我需要呈现如下所示的图表:

enter image description here

始终显示所有工具提示不是一种可接受的方式,因为它们不会以正确的方式呈现:

enter image description here

不幸的是,我还没有找到解决方案。我试过 piece-label 插件,但这有同样的问题,因为它的标签重叠,我无法隐藏某些标签。

这是代码,它使用 piece-label 将标签放置在切片上方来创建我的图表:

private createStatusChart(): void {
const chartData = this.getStatusChartData();

if (!chartData) {
return;
}

const $container = $(Templates.Dashboard.ChartContainer({
ContainerID: 'chart-status',
HeaderText: 'Status'
}));

this._$content.append($container);

const legendOptions =
new Model.Charts.LegendOptions()
.SetDisplay(false);

const pieceLabelOptions =
new Model.Charts.PieceLabelOptions()
.SetRender('label')
.SetPosition('outside')
.SetArc(true)
.SetOverlap(true);

const options =
new Model.Charts.Options()
.SetLegend(legendOptions)
.SetPieceLabel(pieceLabelOptions);

const chartDefinition = new Model.Charts.Pie(chartData, options);
const ctx = this._$content.find('#chart-status canvas').get(0);

const chart = new Chart(ctx, chartDefinition);
}

private getStatusChartData(): Model.Charts.PieChartData {
if (!this._data) {
return;
}

const instance = this;
const data: Array<number> = [];
const labels: Array<string> = [];
const colors: Array<string> = [];

this._data.StatusGroupings.forEach(sg => {
if (!sg.StatusOID) {
data.push(sg.Count);
labels.push(i18next.t('Dashboard.NoStateSet'));
colors.push('#4572A7');

return;
}

const status = DAL.Properties.GetByOID(sg.StatusOID);

data.push(sg.Count);
labels.push(status ? status.Title : i18next.t('Misc.Unknown'));
colors.push(status ? status.Color : '#fff');
});

const dataset = new Model.Charts.Dataset(data).setBackgroundColor(colors);

return new Model.Charts.PieChartData(labels, [dataset]);
}

结果:

enter image description here

最佳答案

有一个新插件(自一年以来),称为 chartjs-plugin-piechart-outlabels

只需导入源代码
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-piechart-outlabels"></script>
并将其与 outlabeledPie 类型一起使用

var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var ctx = document.getElementById("chart-area").getContext("2d");
var myDoughnut = new Chart(ctx, {
type: 'outlabeledPie',
data: {
labels: ["January", "February", "March", "April", "May"],
...
plugins: {
legend: false,
outlabels: {
text: '%l %p',
color: 'white',
stretch: 45,
font: {
resizable: true,
minSize: 12,
maxSize: 18
}
}
}
})

关于javascript - chart.js:在饼图外显示标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45732268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com