【问题标题】:Matplotlib - Updating bar graph with positive and negative valuesMatplotlib - 使用正负值更新条形图
【发布时间】:2016-11-23 01:08:45
【问题描述】:

我正在使用this answer 中描述的方法来动态更新条形图。然而,我想要的条形图应该显示来自零点而不是图表底部的值。这是我的酒吧初始化代码:

oxBar = aBar.bar(0, 200, bottom=-100, width=1)

而且我希望能够从零点正面和负面地更新我的图表。但是,使用上面链接中的方法,我只能让它从图表底部到达一个高度,而不是从零点。例如,输入 -50 应该将条形图从 0 绘制到 -50,但它却将条形图从 -100 绘制到 -50。

【问题讨论】:

  • 为什么不使用bottom=0plt.bar(0, -50, bottom=0, width=1) ?
  • 我可以,但是我想让图形从图形的中点开始,并且使用这种方法总是从底部开始,所以这不能解决问题。
  • 但它从 0 绘制到 -50 - 即。 plt.bar([0,1,2], [-100, -50,100], bottom=0, width=1) 从 0 到 -100 以及从 0 到 100 绘制,0 位于中间。可能您需要其他属性来设置绘图大小。
  • 啊,是的,我明白你在说什么。这在您不必更改数据值时有效,但是当您使用 rect.set_height(h)(如链接问题中所示)时,它似乎只从“底部”中提取
  • 也许可以试试plt.ylim([-200,200])

标签: python matplotlib tkinter


【解决方案1】:

Matplotlib 默认自动调整绘图大小,但您可以将ylim 设置为具有恒定大小/高度,然后0 可以始终位于中间。

例子

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random

def animate(frameno):
    x = random.randint(-200, 200)
    n = [x, -x]

    for rect, h in zip(rects, n):
        rect.set_height(h)

    return rects

# --- init ---

fig, ax = plt.subplots()
rects = plt.bar([0,1], [0,0], width=1)
plt.ylim([-200, 200])

ani = animation.FuncAnimation(fig, animate, blit=True,
                              interval=100, frames=100, repeat=False)
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2019-07-22
    • 2017-12-24
    相关资源
    最近更新 更多