是否可以在chart.js中隐藏分段?

问题描述 投票:0回答:1

我想知道是否可以将行设置为隐藏在chartjs数据集->分段中 像这样:

const down = (ctx, value) => ctx.p0.parsed.y > ctx.p1.parsed.y ? value : undefined;
const up = (ctx, value) => ctx.p0.parsed.y < ctx.p1.parsed.y ? value : undefined;

segment: {
          borderColor: ctx => down(ctx , 'rgb(192,75,75)') || up(ctx, 'rgb(0,255,0)'),
          borderDash: ctx => down(ctx, [5,5]),
          hidden: ctx => down(ctx,false),
        }

也许我应该使用其他样式元素

javascript charts chart.js
1个回答
0
投票

您可以设置颜色:

const ctx = document.getElementById('myChart').getContext('2d');

const data = {
  labels: Array.from({
    length: 10
  }, (_, i) => i), // x-axis labels
  datasets: [{
    label: 'Sample Data',
    data: [0, 2, 1, 3, 2, 4, 3, 5, 4, 6], // Sample data with up and down trends
    borderColor: 'rgb(0,255,0)', // Default color for visible (upward) segments
    segment: {
      borderColor: ctx => {
        const isDown = ctx.p0.parsed.y > ctx.p1.parsed.y;
        return isDown ? 'rgba(0,0,0,0)' : 'rgb(0,255,0)'; // Transparent for down, green for up
      }
    },
    fill: false,
  }]
};

const config = {
  type: 'line',
  data: data,
  options: {
    responsive: true,
    plugins: {
      legend: {
        display: true
      }
    },
    scales: {
      x: {
        title: {
          display: true,
          text: 'X-axis'
        }
      },
      y: {
        title: {
          display: true,
          text: 'Y-axis'
        }
      }
    }
  }
};

new Chart(ctx, config);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="600" height="400"></canvas>

© www.soinside.com 2019 - 2024. All rights reserved.