0

I'm a complete noob to web development. I was working on a flask app which plots multiline charts from pandas dataframe using matplotlib, but I wish to add tooltip to the data points via mpld3. mpld3tooltip example is only for scatter plots. How to do this for multiline plots?

data = {'year': [2010, 2011, 2012, 2013, 2014, 2015, 2016,2017, 2018, 2019],
        'shop1': [10, 21, 20, 10, 23, 30, 31,45, 23, 56],
        'shop2': [10, 21, 20, 10, 12, 30, 78,45, 23, 56],
        'shop3': [10, 21, 20, 10, 34, 98, 31,45, 23, 56],}

df = pd.DataFrame(data)
df = df.set_index('year')
fig, ax = plt.subplots()
df.plot(ax=ax, marker='o')  
plt.grid(True)

mpld3.display()
ArchieTiger
  • 2,083
  • 8
  • 30
  • 45

1 Answers1

-1

It doesn't appear as if mpld3 offers a line plot tooltip, so you have to use the point tooltip and adapt it for line plots. The important observation here is that the point tooltip relies upon matplotlib markers (see discussion here). Obviously for many line plots you may not want markers, so my example below turns off the marker colors. (My example is a modified version of the example for the point tooltip from the official documentation)

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import mpld3
from mpld3 import plugins
import quandl


# Define some CSS to control our custom labels
css = """
table
{
  border-collapse: collapse;
}
th
{
  color: #ffffff;
  background-color: #000000;
}
td
{
  background-color: #cccccc;
}
table, th, td
{
  font-family:Arial, Helvetica, sans-serif;
  border: 1px solid black;
  text-align: right;
}
"""

fig, ax = plt.subplots()

df = quandl.get("YALE/SPCOMP")
ts = df['S&P Composite']

labels = []
for dt in ts.index:
    labels.append( str(dt) + '<br/>' + str(ts.loc[dt]))

lines = plt.plot(ts.index, ts.values, marker='o', ls='-', ms=5, markerfacecolor='None',markeredgecolor='None',)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('HTML tooltips', size=20)

tooltip = plugins.PointHTMLTooltip(lines[0], labels,
                                   voffset=10, hoffset=10, css=css)
plugins.connect(fig, tooltip)

mpld3.display()
C S
  • 1,363
  • 1
  • 17
  • 26