动态分组条形图

时间:2018-05-06 03:14:48

标签: python pandas matplotlib plot

我正在尝试创建一个动态条形图,它会在循环的每次迭代时更新,但图表只在循环完成后才会渲染。有人可以帮忙吗?

import matplotlib.pyplot as plt
import time
from IPython import display
import numpy as np
import pandas as pd 
from pandas import DataFrame, Series
from numpy.random import randn
%matplotlib inline
fig,ax = plt.subplots(1,1)
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
ax.set_xlabel("Load", fontsize=12)
ax.set_ylabel("People", fontsize=12)
y_pos = np.arange(len(people))
ax.set_yticks(y_pos)
ax.set_yticklabels(people, rotation=75)
fig.canvas.draw()
width = 0.4
for i in range(0,3):    
    p1 = 3 + 10 * np.random.rand(len(people))
    p2 = 3 + 10 * np.random.rand(len(people))
    df = DataFrame({'p1': p1, 'p2': p2})
    ax.barh(y_pos, df['p1'], width, color='red')
    ax.barh(y_pos + width, df['p2'], width, color='blue')
    fig.canvas.draw()
    time.sleep(0.5)

1 个答案:

答案 0 :(得分:0)

我想出了答案。问题在于%matplotlib内联语句及其位置。 对于交互式图表,建议使用%matplotlib笔记本而不是内联。它应该在matplotlib导入之前放置。

以下代码有效!

foo