0

Issue: The mouse hover annotation display effect of bars is not working in saved image "foo.png" by plt.savefig('foo.png').

The savefig() function saving the plot as a static image without mouse hover annotation display effect of bars in image.

while mouse hover annotation display effect of bars is working in popup image-box generated by plt.show() function.

full code

import numpy as np
import matplotlib.pyplot as plt

company=['google','amazon','msft','fb']
revenue=[80,68,54,27]

fig=plt.figure()
ax=plt.subplot()

xpos=np.arange(len(company))

bars = plt.bar(xpos,revenue)


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 = "sss ss({:.2g},{:.2g})".format( x,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 bars:
            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()

fig.canvas.mpl_connect("motion_notify_event", hover)

#plt.show()
plt.savefig('foo.png')
user3603533
  • 63
  • 1
  • 1
  • 4
  • savefig will just save the figure before you have a chance to interact with it. You are going to need to set up an event to trigger the save, or use the "save" GUI button – Jody Klymak Feb 23 '23 at 18:09
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – user11717481 Feb 28 '23 at 03:46

0 Answers0