简体   繁体   中英

How do I dynamically set the scale of y-axis for c3 chart?

I'm making a c3 chart that has grouped data, and I'd like to have a y-axis grid line that shows a maximum value, that the grouped data combined should not exceed.

So, the y-axis grid line could be called "Maximum"

I know how to make the grid, but it doesn't always show because the grouped data might be way below the grid value. But I want the grid to always show.

I looked at padding for the y-axis, but it's uses pixels and is hard to get accurate.

Is there a away to just set the y-axis to show like 5 values greater than whatever the y-axis grid line is?

Unfortunately, C3 does not have a setting for "set Y axis to maximum of yvalue or largest data". However, let's assume you have added a grid line using a method like below. You can then set the y-axis padding and maximum value using the settings shown here:

grid: {
    y: {
        lines: [{ value: 20 }], 
    }
},
axis: {
    y: {
        padding: {top:5, bottom,0},
        max: 20
    }
}

In this case I have set the max value to be the same as the gridline value and used padding to create a small space above it. This will handle the case where your data is below the gridline. However, if your data exceeds the (gridline+padding) total then the chart won't grow to accommodate that data because the max setting is fixed. So, you will need to dynamically change this max value using javascript if your data is greater than the max value by finding the maximum value in your data and setting max above that if it exceeds your gridline value, something like this...

if(highValue > gridlineValue)
  chart.axis.max(highValue);
else
  chart.axis.max(gridlineValue);

I just noticed that your data never exceeds the gridline, so you can go with the first part of this answer. I've left the rest in here in case someone else wants a more dynamic solution. Note that you could also just use the max value without padding if you wanted to set it explicitly to a value higher than the gridline.

As of this writing, there actually is a way to reset the y-max to be dynamic, after setting it to specific max. You do so by setting max to undefined , like so: chart.axis.max(undefined); .

Here, have a working jsfiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM