I used this answer to create a bar-plot where you can hover to see the y-value, see code and resulting picture below
import matplotlib.pyplot as plt
import numpy as np
# initialize plot
fig, ax = plt.subplots(nrows=1, ncols=1)
# create barplot
N = 10
ind = np.arange(N)
width = 0.35
bars1 = ax.bar(ind, np.random.randint(1, 10, N), width)
# fix xticks
labels = ['Label{}'.format(i+1) for i in range(N)]
ax.set_xticks(ind)
ax.set_xticklabels(labels, fontsize = 'medium', rotation = 'vertical')
# annotate
annot = ax.annotate("", xy=(0, 0), xytext=(-20, 20), textcoords="offset points",
bbox=dict(boxstyle="round", fc="black", ec="b", lw=2),
arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)
def update_annot(bar):
x = bar.get_x() + bar.get_width() / 2.
y = bar.get_y() + bar.get_height()
annot.xy = (x, y)
text = "({:.2g})".format(y)
annot.set_text(text)
annot.get_bbox_patch().set_alpha(0.4)
def hover(event):
vis = annot.get_visible()
if event.inaxes == ax:
for bar in bars1:
cont, ind = bar.contains(event)
if cont:
update_annot(bar)
annot.set_visible(True)
fig.canvas.draw_idle()
return
if vis:
annot.set_visible(False)
fig.canvas.draw_idle()
# connect annotation to plot
fig.canvas.mpl_connect("motion_notify_event", hover)
However, when exporting to a new excel spreadsheet using these rows
import xlwings as xw
workbook = xw.Book()
worksheet = workbook.sheets['Sheet1']
worksheet.pictures.add(fig)
, the hovering no longer works (in excel). Is it possible to create an interactive plot in matplotlib and export it to excel where the functionality remains?