I am trying to understand interactive plots in matplotlib (in Jupyter Notebook).
Here is a piece of codes and I would like to know why this is not working.
import matplotlib.pyplot as plt
%matplotlib notebook
fig, ax = plt.subplots()
BarChart = ax.bar(df.index, df.mean(axis=1), color = 'black')
def on_click(event):
for Bar in BarChart:
Bar.set_color(color='red')
fig.canvas.mpl_connect('button_press_event', on_click)
plt.show()
Could anybody explain me why this is not updating the color of bars into red and how to fix it?
When the for loop is used in a static case, ie without the on_click and mpl_connect function, it does update the bar colors in the original plot.
I was wondering if I need an expression to explicitly updating the plot.
Bar
is a Rectangle patch, therefore you can use set_color
to change the color of the bars. However, it does not accept color
as a keyword argument. From the docs, the argument you need to use is c
Therefore, you can either remove color=
, or replace it with c=
import matplotlib.pyplot as plt
%matplotlib notebook
fig, ax = plt.subplots()
BarChart = ax.bar(df.index, df.mean(axis=1), color = 'black')
def on_click(event):
for Bar in BarChart:
Bar.set_color('red')
# Bar.set_color(c='red') # this also works
fig.canvas.mpl_connect('button_press_event', on_click)
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.