ChartJS 如何用vuejs在图表中画一条线?

izkcnapc  于 2023-04-30  发布在  Chart.js
关注(0)|答案(1)|浏览(173)

我正在做一个数据可视化项目。我使用Django作为后端,Vue作为前端。我使用chartjs来绘制图表。对于散点图,我需要绘制中线(垂直和水平)。通过跟踪其中一个tutorials,我了解到我需要添加一个插件。我尝试了不同的方法来启动插件:作为一种方法或计算。或者只是将其添加到插件。

<template>
       <Scatter :style="{ height: '400px' }" :data="chartData" :options="chartOptions" />
</template>

<script>
import {
  Chart as ChartJS,
  LinearScale,
  PointElement,
  LineElement,
  Tooltip,
  Legend
} from 'chart.js'
import { Scatter } from 'vue-chartjs'

ChartJS.register(LinearScale, PointElement, LineElement, Tooltip, Legend)

export default {
    name: 'ScatterChart',
    components: {
        Scatter
    },
    props: {
        homeTeam: Boolean,
        playerStats: Array,
    },
    mounted() {

    },
    watch: {
        playerStats() {
            this.setDataSets();
        }
    },
    methods: {
        setDataSets() {
            this.datasets = [];
            this.playerStats.forEach(player => {
                let dataset = {
                    label: player.player_name,
                    data: [
                        {
                            x: player.attack,
                            y: player.defense
                        }
                    ],
                    backgroundColor: this.bgColor
                };
                this.datasets.push(dataset);
            });
        },
    },
    computed: {
        chartData() {
            return {
                datasets:
                    this.datasets
            }
        },
        chartOptions() {
            return {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        type: 'linear',
                        position: 'bottom',
                        title: {
                            display: true,
                            text: 'Attack',
                        },
                    },
                    y: {
                        type: 'linear',
                        position: 'left',
                        title: {
                            display: true,
                            text: 'Defense',
                        },
                    }
                },
                plugins: [
                    {
                        id: 'horizontalMedianLine',
                        beforeDraw (chart) {
                            console.log('horizontalMedianLine called');
                            const yScale = chart.scales['y'];
                            const xScale = chart.scales['x'];
                            const ctx = chart.ctx;
                            const yValue = yScale.getPixelForValue(1.25);
                            const xValue = xScale.getPixelForValue(2.5);
                            console.log('yValue:', yValue);
                            console.log('xValue:', xValue);
                            ctx.save();
                            ctx.beginPath();
                            ctx.moveTo(xScale.left, yValue);
                            ctx.lineTo(xScale.right, yValue);
                            ctx.moveTo(xValue, yScale.top);
                            ctx.lineTo(xValue, yScale.bottom);
                            ctx.setLineDash([5, 5]);
                            ctx.strokeStyle = 'red';
                            ctx.lineWidth = 2;
                            ctx.stroke();
                            ctx.restore();
                        },
                    },
                ],
            }
        },
    },
    data() {
        return {
            datasets: [],
            bgColor: this.homeTeam ? 'rgb(255, 99, 132)' : 'rgb(54, 162, 235)',
        }
    },
}
</script>

因此,我希望在图表上看到两条线:

我做错了什么?请帮帮我

g2ieeal7

g2ieeal71#

您放错了内联插件对象。它不应该在options下,而应该在用于构造图表的对象的顶层。
在您的设置中,指定插件的一种可能方法是声明一个计算方法chartPlugins

computed: {
    chartData(){
        return {
            datasets: this.datasets,
        };
    },
    chartPlugins(){
        return [{
            id: "horizontalMedianLine",
            
            beforeDraw(chart){
                //......
            }
        }]
    }
}

并在模板中使用:

<template>
  <Scatter
    :style="{ height: '400px' }"
    :plugins="chartPlugins"
    :data="chartData"
    :options="chartOptions"
  />
</template>

而且,你不需要一个插件来绘制这些线条;使用两个新的数据集来实现这一目标会更有效。这是水平的:

methods: {
    setDataSets(){
        this.datasets = [];
        chartConfig.playerStats.forEach((player) => {
            //.......
        });
        const attack = this.playerStats.map(({attack}) => attack);
        this.datasets.push({
            borderColor: 'red',
            showLine: true,
            pointRadius: 0,
            segment: {borderDash: [5, 5]},
            data: [[Math.min(...attack), 1.25], [Math.max(...attack), 1.25]]
        });
    }
}

相关问题