获取matplotlib图以更新新数据

时间:2018-12-21 02:46:33

标签: python pandas matplotlib graph

我有下面的代码,该代码从csv文件中读取数据并使用matplotlib创建图形。正在使用的csv文件会定期更新,并且图形也会进行更新以反映这一点。

import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

objects = ("a","b","c","d","e","f","g","h")

def update_graph():
    fig.clear()
    cols = ["a","b","c","d","e","f","g","h"]
    df = pd.read_csv("C:/Users/user/Dropbox/sent_proj/live_info.csv",header=None,  names=cols,encoding = "UTF-8",low_memory=False)
    performance = df.values.tolist()
    flat_list = [int(item) for sublist in performance for item in sublist]
    a = np.array(flat_list)
    y_pos = np.arange(len(objects))
    mask1 = a < 0
    mask2 = a >= 0
    plt.axhline(0, color='black')
    plt.bar(y_pos[mask1], a[mask1], align='center', color = 'r', width= 1, edgecolor = "black", linewidth = 1)
    plt.bar(y_pos[mask2], a[mask2], align='center', color = 'g', width= 1, edgecolor = "black", linewidth = 1)
    plt.xticks(y_pos, objects)
    fig.canvas.draw()
    win.after(20000, update_graph)

fig = plt.figure()
win = fig.canvas.manager.window
win.after(100, update_graph)
plt.show()

我想通过单击图并显示一些数据来加以补充,这些数据通过改编我发现的代码而可以使用。问题是我无法再对其进行更新。目前,我对此图有误。

win = fig.canvas.manager.window

AttributeError:'FigureManagerInterAgg'对象没有属性'window'

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

objects = ("a","b","c","d","e","f","g","h")

def update_graph():
    fig.clear()
    cols = ["a", "b", "c", "d", "e", "f", "g", "h"]
    df = pd.read_csv("live_info.csv", header=None, names=cols, 
    encoding="UTF-8", low_memory=False)
    performance = df.values.tolist()
    flat_list = [int(item) for sublist in performance for item in sublist]
    a = np.array(flat_list)
    y_pos = np.arange(len(objects))
    ax2.axhline(0, color='black')
    mask1 = a < 0
    mask2 = a >= 0
    bars = ax2.bar(y_pos[mask1], a[mask1], align='center', color = 'r', width= 1, edgecolor = "black", linewidth = 1, picker=True)
    bars = ax2.bar(y_pos[mask2], a[mask2], align='center', color = 'g', width= 1, edgecolor = "black", linewidth = 1, picker=True)
    plt.xticks(y_pos, objects)
    for label in ax2.get_xticklabels():  # make the xtick labels pickable
        label.set_picker(True)

    fig.canvas.draw()
    win.after(20000, update_graph)

def onpick1(event):
    (on mouse click stuff)


fig, ax2 = plt.subplots(1)
win = fig.canvas.manager.window
fig.canvas.mpl_connect('pick_event', onpick1)
win.after(100, update_graph)
plt.show()

是否可以像以前一样更新我的新代码?我该怎么做呢?预先感谢

0 个答案:

没有答案