Updating a matplotlib bar graph?

匿名 (未验证) 提交于 2019-12-03 00:52:01

问题:

I have a bar graph which retrieves its y values from a dict. Instead of showing several graphs with all the different values and me having to close every single one, I need it to update values on the same graph. Is there a solution for this?

回答1:

Here is an example of how you can animate a bar plot. You call plt.bar only once, save the return value rects, and then call rect.set_height to modify the bar plot. Calling fig.canvas.draw() updates the figure.

import matplotlib matplotlib.use('TKAgg') import matplotlib.pyplot as plt import numpy as np  def animated_barplot():     # http://www.scipy.org/Cookbook/Matplotlib/Animations     mu, sigma = 100, 15     N = 4     x = mu + sigma*np.random.randn(N)     rects = plt.bar(range(N), x,  align = 'center')     for i in range(50):         x = mu + sigma*np.random.randn(N)         for rect, h in zip(rects, x):             rect.set_height(h)         fig.canvas.draw()  fig = plt.figure() win = fig.canvas.manager.window win.after(100, animated_barplot) plt.show() 


回答2:

I've simplified the above excellent solution to its essentials, with more details at my blogpost:

import numpy as np import matplotlib.pyplot as plt  numBins = 100 numEvents = 100000  file = 'datafile_100bins_100000events.histogram' histogramSeries = np.fromfile(file, int).reshape(-1,numBins)  fig, ax = plt.subplots() rects = ax.bar(range(numBins), np.ones(numBins)*40)  # 40 is upper bound of y-axis   for i in range(numEvents):     [rect.set_height(h) for rect,h in zip(rects,histogramSeries[i,:])]     fig.canvas.draw()     plt.pause(0.001) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!