Search code examples
javascriptchartschart.js

Is it possible to hide segments in chart.js?


I wonder if I can set the lines to be hidden in chartjs datasets->segment, like this:

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),
        }

Maybe I should use other styling element?


Solution

  • You can set the color to transparent - I tried to use the borderwidth, but that did not seem to work as well as transparent did:

    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>