Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it posible to hide segment 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading