1
votes

I'm using ChartJS to build a bar chart. My chart contains one bar for each week of the year. I would like the tooltips of each bar to display "Week 15 (Apr 10 - Apr 16)" for example, while the corresponding label in the x-axis should display only the week number, so "15".

This answer describes exactly what I want to accomplish, though I'm using a bar chart, not a scatterplot. I tried that method on my bar chart and extracted the week number form the label I added to the dataset ("Week 15 (Apr 10 - Apr 16)" --> "15"). However, the userCallback function overrides both the x-axis labels and the tooltip label with the value "15". Can someone show me how I can modify only the x-axis label of each bar (without affecting the tooltip label) or suggest an alternative approach?

EDIT: fiddle with my code: https://jsfiddle.net/96z57gqf/. The x-axis label is correct, but I need the bar tooltip to keep the original value ("Week 12", "Week 13" and so on).

xAxes: [{
  ticks: {
    userCallback: function(value, index, values) {
      return value.replace("Week ","");
    }
  }
}]

EDIT2/SOLUTION: See https://jsfiddle.net/3ft4wrL9/. From the Vinod's answer below, I modified my options to include:

tooltips: {
    mode: 'index',
    intersect: true,
    callbacks: {
      title: function(tooltipItem, data) {
        return data["labels"][tooltipItem[0]["index"]];
      }
    }
  },
1
Can you post your code in fiddle?Vinod Louis
Please provide your codeSanyami Vaidya
Added code to the question description.André de Brito
@AndrédeBrito See my answer you can use tooltip like this jsfiddle.net/96z57gqf/2 use your formattingVinod Louis

1 Answers

0
votes

If you are using chart.js 2 then you can use the tooltip callback method documented here like this inside options in order to customize your tooltip

tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                //TODO return what you want using value of tooltipItem and data 
            }
        }
    }