Chartjs,气泡图,数据标签中重复值的定位问题
Posted
技术标签:
【中文标题】Chartjs,气泡图,数据标签中重复值的定位问题【英文标题】:Chartjs, Bubble Chart, positioning problem with duplicate value in data labels 【发布时间】:2021-10-27 23:29:41 【问题描述】:数据标签中有重复值 - 有没有办法在气泡图中的第一个或第二个重复值上绘制气泡?
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
var ctx = document.getElementById("myChart");
var options = responsive: true,
maintainAspectRatio: false,
;
var mixedChart = new Chart(ctx,
type: 'bar',
data:
labels: ["1", "2", "1", "4"], //Same Value on First and Third Position
datasets: [
//Lines
label: "First_Line",
type: "line",
borderColor: "#8e5ea2",
data: [5,10,7,12],
fill: false
,
label: "Second_Line",
type: "line",
borderColor: "#3e95cd",
data: [1,4,15,6],
fill: false
,
//Bubbles
label: "Bubble_One",
type: "bubble",
backgroundColor: "#8e5ea2",
data: [ x: "2", y: 10, r: 15],
,
label: "Bubble_Two",
type: "bubble",
backgroundColor: "#3e95cd",
backgroundColorHover: "#3e95cd",
data: [x: ???, y: 6, r: 15] //First "1" or Second "1" possible?
]
,
options: options
);
</script>
不幸的是,像 "1"[0] 这样的东西不起作用。
【问题讨论】:
【参考方案1】:你不能直接这样做 afaik 但你可以在标签中添加一个额外的部分并使用工具提示和轴的回调将其过滤掉:
<canvas id="myChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
var ctx = document.getElementById("myChart");
var options =
responsive: true,
maintainAspectRatio: false,
scales:
x:
offset: false,
ticks:
callback: function(val)
return this.getLabelForValue(val).split('-')[0]
,
plugins:
tooltip:
callbacks:
label: (ttItem) =>
if (ttItem.dataset.type === "bubble")
return `$ttItem.label: ($ttItem.raw.x.split('-')[0],$ttItem.raw.y)`
else if (ttItem.dataset.type === "line")
return `$ttItem.dataset.label: $ttItem.parsed.y`
,
title: (ttItem) => (ttItem[0].label.split('-')[0])
;
var mixedChart = new Chart(ctx,
type: 'bar',
data:
labels: ["1-1", "2", "1-2", "4"], //Same Value on First and Third Position
datasets: [
//Lines
label: "First_Line",
type: "line",
borderColor: "#8e5ea2",
data: [5, 10, 7, 12],
fill: false
,
label: "Second_Line",
type: "line",
borderColor: "#3e95cd",
data: [1, 4, 15, 6],
fill: false
,
//Bubbles
label: "Bubble_One",
type: "bubble",
backgroundColor: "#8e5ea2",
data: [
x: "2",
y: 10,
r: 15
],
,
label: "Bubble_Two",
type: "bubble",
backgroundColor: "#3e95cd",
backgroundColorHover: "#3e95cd",
data: [
x: "1-2",
y: 6,
r: 15
] //First "1" or Second "1" possible?
]
,
options: options
);
</script>
【讨论】:
好的,谢谢,如果没有其他方法我会尝试这样的以上是关于Chartjs,气泡图,数据标签中重复值的定位问题的主要内容,如果未能解决你的问题,请参考以下文章