sgratzl / chartjs-chart-boxplot

Chart.js Box Plots and Violin Plot Charts
https://www.sgratzl.com/chartjs-chart-boxplot/
MIT License
101 stars 23 forks source link

Correct Tooltip modification technique #8

Closed Djones4822 closed 2 years ago

Djones4822 commented 2 years ago

I'm having an issue modifying the tooltip, I was requested to add dollar signs before each value, to do this I ended up pulling the default tooltip callback out of the Chart.BoxPlot.js file and modifying it in the options of my chart instance. However, this also required that I pull out the toFixed function as well.

This works, and I was able to add my dollar sign, but it felt a bit hacky, I was wondering if there is an intended procedure for this?

Codepen of this in action: https://codepen.io/djones4822/pen/MWmbBqa

Code used:

Extracted from BoxPlot, add anywhere in your js file:

  function toFixed(value) {
    var decimals = this._chart.config.options.tooltipDecimals; // inject number of decimals from config

    if (decimals == null || typeof decimals !== 'number' || decimals < 0) {
      return value;
    }

    return Number.parseFloat(value).toFixed(decimals);
  }

Add to the options section of the chart definition:

//existing options code
tooltips: {
        callbacks: {
          boxplotLabel: function boxplotLabel(
            item,
            data,
            b,
            hoveredOutlierIndex
          ) {
            var datasetLabel = data.datasets[item.datasetIndex].label || "";
            var label = ""
              .concat(datasetLabel, " ")
              .concat(
                typeof item.xLabel === "string" ? item.xLabel : item.yLabel
              );

            if (!b) {
              return "".concat(label, " (NaN)");
            }

            if (hoveredOutlierIndex >= 0) {
              var outlier = b.outliers[hoveredOutlierIndex];
              return ""
                .concat(label, " (outlier: ")
                .concat(toFixed.call(this, outlier), ")");
            }

            return ""
              .concat(label, " (min: $")
              .concat(toFixed.call(this, b.min), ", q1: $")
              .concat(toFixed.call(this, b.q1), ", median: $")
              .concat(toFixed.call(this, b.median), ", q3: $")
              .concat(toFixed.call(this, b.q3), ", max: $")
              .concat(toFixed.call(this, b.max), ")");
          }
        }
      }
// remaining options
sgratzl commented 2 years ago

the version that you are using in your codepen is the original and not this forked version. Please ask your question in the original repository instead, since this fork as highly changed in the mean time