我正在尝试使用 vue-chart-3/chart.js 制作堆叠图表。我想要一张这样的图表:
但我不确定我做错了什么,我创建的图表正在并排堆叠条形图:
图表数据:
{ “标签”: [ “2020-10”, “2020-11”,
“2023-04”, “2023-05”, “2023-06”, “2023-07” ], “数据集”:[ { “标签”:“above_120”, “数据”: [ 0, 0, 0, 0,7.9597462909733085, 10.92147729254032, 12.128219538943902, 13.092781081826708, 16.982628499580606, 17.622395653806972, 36.51382339697158, 45.423623102032764, 58.474440088803384 ], "backgroundColor": "#1E5662", "stack": "stackabove_120" }, { "label": "up_to_120", "data": [ 0, 0, 15.875881135502462, 3.165108353314404 ], "backgroundColor": "#3E300D", "stack": "stackup_to_120" }, { "label": "up_to_90", "data": [ 0, 0, 0, 0, 0, 6.197500821665821, 8.2908889492772 ], "backgroundColor": "#DBD383", "stack": "stackup_to_90" }, { "label": "up_to_60", "data": [ 0, 0, 0, 0, 0, 0, 1.5561216578540855, 0, 0, 0, 0, 0, 0, 3.376176540913938 ], "backgroundColor": "#0A35AC", "stack": "stackup_to_60" }, { "label": "up_to_30", "data": [ 0, 0, 11.186721091033386, 0, 0, 1.7895529268699548, 0, 0, 0, 0, 0.06295971365877787, ], "backgroundColor": "#AE95B3", "stack": "stackup_to_15" } ] }
我尝试使用 stacked: true
> const chartOptions = ref( { scales: {
> yAxes: [{
> ticks: {
> beginAtZero: true
> },
> stacked: true
> }],
> xAxes: [{
> stacked: true,
> }] } } );
但是没有成功
完整组件:
<template>
<div>
<BarChart :chartData="barChartData" :chartOptions="chartOptions" />
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { BarChart } from "vue-chart-3";
import { Chart, registerables, ChartData } from "chart.js";
Chart.register( ...registerables );
interface DataObject {
label: string;
data: {
above_120: number;
up_to_120: number;
up_to_90: number;
up_to_60: number;
up_to_30: number;
up_to_15: number;
};
}
const props = defineProps( {
data: {
type: Array,
required: true
}
} );
const barChartData = ref<ChartData>( {
labels: [],
datasets: []
} );
handleChartData();
const chartOptions = ref( {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
},
stacked: true
}],
xAxes: [{
stacked: true,
}]
}
} );
function handleChartData () {
const chartData: Array<DataObject> = props.data;
if ( chartData ) {
const labels: Array<string> = [];
const datasets: Array<ChartData> = [];
const legendKeys = Object.keys( chartData[0].data );
const dataArrays: { [key: string]: Array<number> } = {};
for ( const key of legendKeys ) {
dataArrays[key] = [];
}
for ( const dataObj of chartData ) {
labels.push( dataObj.label );
for ( const [key, value] of Object.entries( dataObj.data ) ) {
dataArrays[key].push( value );
}
}
for ( const key of legendKeys ) {
datasets.push( {
label: key,
data: dataArrays[key],
backgroundColor: randomColor(),
stack: `stack${key}`
} );
}
barChartData.value = {
labels: labels,
datasets: datasets
};
}
}
function randomColor () {
const letters = '0123456789ABCDEF';
let color = '#';
for ( let i = 0; i < 6; i++ ) {
color += letters[Math.floor( Math.random() * 16 )];
}
return color;
}
</script>