Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update barchart in matplotlib?

I have bar chart, with a lot of custom properties ( label, linewidth, edgecolor)

import matplotlib.pyplot as plt
fig = plt.figure()
ax  = plt.gca()

x = np.arange(5)
y = np.random.rand(5)

bars = ax.bar(x, y, color='grey', linewidth=4.0)

ax.cla()
x2 = np.arange(10)
y2 = np.random.rand(10)
ax.bar(x2,y2)
plt.show() 

With 'normal' plots I'd use set_data(), but with barchart I got an error: AttributeError: 'BarContainer' object has no attribute 'set_data'

I don't want to simply update the heights of the rectangles, I want to plot totally new rectangles. If I use ax.cla(), all my settings (linewidth, edgecolor, title..) are lost too not only my data(rectangles), and to clear many times, and reset everything makes my program laggy. If I don't use ax.cla(), the settings remain, the program is faster (I don't have to set my properties all the time), but the rectangles are drawn of each other, which is not good.

Can you help me with that?

like image 910
user3598726 Avatar asked Jul 19 '17 09:07

user3598726


Video Answer


1 Answers

In your case, bars is only a BarContainer, which is basically a list of Rectangle patches. To just remove those while keeping all other properties of ax, you can loop over the bars container and call remove on all its entries or as ImportanceOfBeingErnest pointed out simply remove the full container:

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax  = plt.gca()

x = np.arange(5)
y = np.random.rand(5)

bars = ax.bar(x, y, color='grey', linewidth=4.0)

bars.remove()
x2 = np.arange(10)
y2 = np.random.rand(10)
ax.bar(x2,y2)
plt.show()
like image 198
jotasi Avatar answered Sep 29 '22 16:09

jotasi