【问题标题】:How to update barchart in matplotlib?如何更新 matplotlib 中的条形图?
【发布时间】:2017-12-24 10:54:15
【问题描述】:

我有条形图,有很多自定义属性(标签、线宽、边缘颜色)

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'

我不想简单地更新矩形的高度,我想绘制全新的矩形。如果我使用 ax.cla(),我的所有设置(线宽、边缘颜色、标题..)也会丢失,不仅是我的数据(矩形),而且要清除很多次,并重置所有内容会使我的程序滞后。如果我不使用ax.cla(),设置仍然存在,程序更快(我不必一直设置我的属性),但是矩形是相互绘制的,这不好。

你能帮我解决这个问题吗?

【问题讨论】:

    标签: python matplotlib plot bar-chart


    【解决方案1】:

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

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

    【讨论】:

    • 为什么要一个接一个地移除bar而不是直接移除整个BarContainer,bars.remove()
    • 我已经尝试过你的解决方案:循环通过'bars',并一步删除条形。在新的 ax.bar(x2,y2) 之后,矩形再次变为蓝色,但我的其他设置(当然不是矩形相关的),如标题,y,x lims 保持不变,谢谢!
    猜你喜欢
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    相关资源
    最近更新 更多