2

How does one plot Pandas line plots where there are tooltips indicating both the label of the line and the value of the point the mouse is over?

A pandas plot may have a dozen different lines with different legend labels. The tooltip should output (label, value). If this is too much to ask, then just the label is fine.

I have a preference for mpld3 but any other plotting package is ok. In mpld3, do you use PointLabelTooltip or LineLabelTooltip to work for pandas plots? Please provide an example code.

The following code gives an error, because the PointLabelTooltip is expecting points, not lines:

import mpld3
mpld3.enable_notebook()
fig, ax = plt.subplots()
df = pd.DataFrame(np.cumsum(np.random.normal(0,1,(12,1000)),axis=1).T)
axes = df.plot(figsize=(14,4), colormap='spectral');

labels = list(df.columns.values)
tooltip = mpld3.plugins.PointLabelTooltip(axes.get_lines()[0],labels=labels)
mpld3.plugins.connect(fig, tooltip) 

Javascript error adding output!
TypeError: null is not an object (evaluating 'obj.elements')
See your browser Javascript console for more details.
mikal94305
  • 4,663
  • 8
  • 31
  • 40
  • You might want to check that [link](http://stackoverflow.com/questions/14338051/matplotlib-cursor-snap-to-plotted-data-with-datetime-axis). It seems to provide a function that snaps the cursor to the nearest data point. This point can then be identified as element of a certain curve. – RaJa May 24 '15 at 07:13

1 Answers1

3

To put a simple tooltip on a line, you can use mpld3.plugin.LineLabelTooltip. You must do it once for each line. Here is a modified version of your code:

import mpld3, pandas as pd
mpld3.enable_notebook()

df = pd.DataFrame(np.cumsum(np.random.normal(0,1,(5,1000)),axis=1).T)
axes = df.plot(figsize=(14,4), colormap='spectral');

labels = list(df.columns.values)
for i in range(len(labels)):
    tooltip = mpld3.plugins.LineLabelTooltip(axes.get_lines()[i], labels[i])
    mpld3.plugins.connect(plt.gcf(), tooltip) 
Abraham D Flaxman
  • 2,969
  • 21
  • 39
  • 3
    Worked beautifully. Thank you. Guess there is not a way to also have a PointLabelTooltip to display the point value also? – mikal94305 May 30 '15 at 06:39