如何在matplotlib中更新条形图? [英] How to update barchart in matplotlib?

查看:145
本文介绍了如何在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() 

对于正常"绘图,我将使用set_data(),但是对于条形图,我会遇到一个错误:AttributeError: 'BarContainer' object has no attribute 'set_data'

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

我不想简单地更新矩形的高度,我想绘制全新的矩形.如果我使用ax.cla(),我的所有设置(线宽,边缘颜色,标题..)不仅会丢失数据(矩形),而且会丢失很多次并重置所有内容,这会使我的程序步履蹒跚.如果我不使用ax.cla(),则设置会保留下来,程序会更快(我不必一直设置属性),但是矩形会相互绘制,这是不好的.

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.

您能帮我吗?

推荐答案

在您的情况下,bars只是一个BarContainer,它基本上是Rectangle修补程序的列表.要在保留ax的所有其他属性的同时删除它们,可以遍历bar容器并对其所有条目调用remove,或者如ImportanceOfBeingErnest指出的那样,只需删除完整的容器即可:

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()

这篇关于如何在matplotlib中更新条形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆