3

I have a tooltip question about the example in this link D3.JS: Multiseries line chart with mouseover tooltip In this example, the tooltips just show the the data on y axis which are Fahrenheit degrees. But in my project, I also want to see the data which is not displayed on x and y axis.

In this example, I made a change on line 84 based on the code in the link above to generate celsius (°C). How can I have the tooltips show both Fahrenheit and celsius degrees together in a single tooltip? [see fiddle][2]https://jsfiddle.net/xn1sLbf4/3/ Here I am just trying to insert a 'column' of data. In my case, 'celsius' is not something that I can calculate from the data on y-axis. It might be department name, id and etc.

Does anybody know how to do this? Any help is appreciated!

Community
  • 1
  • 1

1 Answers1

3

The tooltip's text is set on lines 250-251:

d3.select(this).select('text')
  .text(y.invert(pos.y).toFixed(2));

So whatever you pass into the .text() method is what those tooltips will display. To show both temperature units, you can modify that code to something like

var fahrenheit = y.invert(pos.y);
var celsius = (fahrenheit - 32) * 5/9;
d3.select(this).select('text')
  .text(fahrenheit.toFixed(1) + "F / " + celsius.toFixed(1) + "c");
meetamit
  • 24,727
  • 9
  • 57
  • 68
  • Thanks for your replying. I guess my example is not very good. Here I am just trying to insert a 'column' of data. In my case, 'celsius' is not something that I can calculate from the data on y-axis. It might be department name, id and etc. – user6030945 Mar 07 '16 at 20:53
  • @user6030945 the answer still applies. Instead of calculating `celsius` you need to get extra data from wherever it's stored it (assuming it's stored in a var already on the client — not on the server). How to do this depends on your specific case. But note that you have access to `d` (try inserting `console.log(d)` on line 250) which may already hold the data you're trying to access. And if it doesn't, maybe you can hang the data on that `d` (via `newCities`) so that you can easily access it. – meetamit Mar 07 '16 at 21:24
  • I changed the line 254 to t.append('tspan').attr('x', '0').attr('y', '0.5em').text(d.values[i].y1.toFixed(2) + '°C'); But the celsius does not change when mouse move. I think the [i] after d.values is not correct. I don't know hoe to access to y1 inside the values. Actually, I have exactly the same data structure as newCities. Sorry for this simple question. Appreciate your help! – user6030945 Mar 07 '16 at 22:00
  • @user6030945 instead of `i`, use `idx`, which is derived above. `console.log(d.values[idx].y1)` – meetamit Mar 08 '16 at 05:21