2

I'm still a beginner and I'm trying to make the edge of the bar of the chart be highlighted (change color) in a mouse movement event when hovering over it. Only the bar over which the mouse hovers should be highlighted. The code shows an error: AttributeError: 'NoneType' object has no attribute 'patch'.

How it should look with the movement of the mouse over the bar.

enter image description here

import seaborn as sb
import matplotlib.pyplot as plt
import matplotlib.patches
%matplotlib qt

df = sb.load_dataset('titanic')

f, ax = plt.subplots(figsize=(6, 4))
ax = sb.barplot(data = df, y = 'class', x = 'fare')#, edgecolor='k')
ax.grid(linestyle='--', zorder=0, axis='x')
f.tight_layout()

def hover(event):
    if event.y:
       event.inaxes.patch.set_edgecolor('k')

ax.figure.canvas.mpl_connect('motion_notify_event', hover)

I tried to make hovering the mouse over a bar of the graph, the same if highlighted from the others create an outline (border) in it.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
MJAGO
  • 35
  • 5
  • Maybe [Display the value of each bar when cursor hovered](https://stackoverflow.com/questions/70792156/display-the-value-of-each-bar-when-cursor-hovered-on-that-bar-in-matplotlib) is of interest? – JohanC Nov 11 '22 at 19:13
  • No, this is a simple example, in my real life, it has more than 15 bars next to each other and with labels of people's names, so it's interesting to highlight the bar or maybe even the y-axis label (maybe with a color different, I hadn't thought of that), but I couldn't even get that one. – MJAGO Nov 11 '22 at 19:17
  • 1
    You may want to consider a plotting tool like bokeh or plotly instead. Also, I don't think the bar highlighting is particularly helpful, but hover annotations might be. See [How to add a hovering annotation on a bar plot with mplcursors](https://stackoverflow.com/a/66320623/7758804) – Trenton McKinney Nov 11 '22 at 19:28
  • No doubt TrentonMcKinney, though, I'm studying matplotlib and seaborn, would it be easier in those 2 libraries? – MJAGO Nov 11 '22 at 19:32
  • The link shows hover annotations for matplotlib / seaborn – Trenton McKinney Nov 11 '22 at 19:33
  • 1
    Thanks TrentonMcKinney, I'll take a look at this link, it might help me with what I need. In the real case, there is another click event where the records are shown when clicking on each bar, but this one I managed to do. Therefore, I would like to highlight the bar. – MJAGO Nov 11 '22 at 19:48

0 Answers0