0

Although similar To this mouseover question, need solution using matplotlib mpld3 HTML tools. This code displays two plots, but only the second one has mouseover annotations. How to get tooltips on both plots?

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

# 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, ax1 = plt.subplots()
ax1.grid(True, alpha=0.3)

N = 100
r = range(N)
df1 = pd.DataFrame(index=r)
df2 = pd.DataFrame(index=r)

r2 = range(N/2)
df1['x'] = r
df1['y'] = r2 + list(reversed(r2))

df2['x'] = range(N)
df2['y'] = [ i*0.1 for i in list(reversed(r2))+r2 ]

labels1 = []
labels2 = []

for i in range(N):
    label1 = df1.ix[[i], :].T
    label2 = df2.ix[[i], :].T

    label1.columns = ['Row {0}'.format(i)]
    label2.columns = ['Row1 {0}'.format(i)]
    # .to_html() is unicode; so make leading 'u' go away with str()
    html1 = str(label1.to_html())
    html2 = str(label2.to_html())
    labels1.append(html1)
    labels2.append(html2)

points1 = ax1.plot(df1.x, df1.y, marker='o', ls='-', lw=4, color='b',
                 mec='k', alpha=.6, label='Line1')

ax2 = ax1.twinx()
ax2.patch.set_alpha(0)

points2 = ax2.plot(df2.x, df2.y, marker='o', ls='-', lw=4, color='r',
                 mec='k', alpha=.6, label='Line2')

ax1.set_xlabel('x')
ax1.set_ylabel('y1')
ax1.set_title('HTML tooltips', size=20)

ax2.set_ylabel('y2')
lns = points1 + points2

labs = [l.get_label() for l in lns]
plt.legend(lns, labs, loc=0)

tooltip1 = plugins.PointHTMLTooltip(points1[0], labels1,
                                   voffset=10, hoffset=10, css=css)

tooltip2 = plugins.PointHTMLTooltip(points2[0], labels2,
                                   voffset=10, hoffset=10, css=css)

plugins.connect(fig, tooltip1, tooltip2)

displayHTML(mpld3.fig_to_html(fig))
runrig
  • 6,486
  • 2
  • 27
  • 44
  • 1
    I would like to mention that while both questions are about the same user-facing problem, the solution must necessarily be entirely different, because here, the tooltips are generated by mpld3 in JavaScript, while in the linked question it's all about matplotlib in python. – ImportanceOfBeingErnest Nov 22 '19 at 01:08
  • I am starting to think the solution to this may involve fixing the mpld3 library. – runrig Nov 25 '19 at 18:58

0 Answers0