1

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"]];
      }
    }
  },
Community
  • 1
  • 1

1 Answers1

0

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 
            }
        }
    }
Vinod Louis
  • 4,812
  • 1
  • 25
  • 46
  • I'm not sure that will solve my problem. The thing is I want to have more information in the tooltip than in the x-axis label, so if I format the label the way I want (with just the week number), then I won't have enough information to build the tooltip string (which is "Week 15 (Apr 10 - Apr 16)"). Unless of course there's a way for me to store metadata than I can then access inside the function you mention and use it to build the tooltip string. – André de Brito Apr 12 '17 at 12:45
  • try to see tooltipItem, data it will surely have enough data you can do if you post your fiddle with your data that can help do you have info of Week or you want to generate it run time liek for week 15 (Apr 10 to Apr 16) is that with you in data or you wanna generate runtime – Vinod Louis Apr 12 '17 at 12:46
  • @AndrédeBrito Do you have definition of week to date ? – Vinod Louis Apr 12 '17 at 12:57
  • Ok, this works, thanks! I needed to use 'title' instead of 'label' to accomplish what I wanted. Here's an update of my original fiddle: https://jsfiddle.net/3ft4wrL9/ – André de Brito Apr 12 '17 at 13:07