chartjs / chartjs-plugin-annotation

Annotation plugin for Chart.js
MIT License
603 stars 325 forks source link

Fixed sized & position annotations #766

Closed fnzr closed 2 years ago

fnzr commented 2 years ago

I have a graph with wildly varying Y scale.

I want to position labels in the chart at a fixed size, for example, drawing a 30px height box. From the docs, I only found the yMax and yMin options, but trying to use them doesn't work for my case, because on certain conditions the resulting box is super small and on other is gigantic.

For example, for a Y scale of 2000, yMin = 200 looks small and nice, but for a Y scale of 300, yMin = 200 takes 75% of the graph. Is there a way to config the annotation to have a fixed size regardless of the chart's scale?

stockiNail commented 2 years ago

@fnzr the plugin is designed to add annotations based on the data values and not in pixels.

Nevertheless you can use you yMin and yMax options as scriptable in order to calculate the best value to fit the annotation on the chart.

box: {
  type: 'box',
  yMin: 45,
  yMax({chart}) {
    const scale = chart.scales.y;
    const size = scale.height * 0.1; // 10% of scale height
    const pxMin = scale.getPixelForValue(45);
    const pxMax = Math.min(pxMin - size);
    const newValue = scale.getValueForPixel(pxMax);
    return newValue;
  },
  xMin: 'Feb',
  xMax: 'Apr',
  borderColor: 'black',
  borderWidth: 2,
},

In the codepen https://codepen.io/stockinail/pen/WNzboVQ you can see an example how the annotation will always have got an height of 10% of scale.

fnzr commented 2 years ago

Thanks. I think this solution works well enough for me. Feel free to close the issue.