【问题标题】:How to update a graph using matplotlib如何使用 matplotlib 更新图形
【发布时间】:2015-10-13 17:56:15
【问题描述】:

我正在使用 Panda 和 matplotlib 在 Python 中绘制图形。 我想要一个实时更新的间隙。这是我的代码:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy as np
import MySQLdb
import pandas

def animate():

    conn = MySQLdb.connect(host="localhost", user="root", passwd="", db="sentiment_index", use_unicode=True, charset="utf8")
    c = conn.cursor()
    query = """ SELECT t_date , score FROM mytable where t_date BETWEEN Date_SUB(NOW(), Interval 2 DAY) AND NOW()"""
    c.execute(query)
    rows=c.fetchall()
    df = pandas.read_sql(query, conn, index_col=['t_date'])

    df.plot()
    plt.show()

animate()

我考虑过使用 FuncAnimation,但没有得到正确的结果。有什么帮助吗?

【问题讨论】:

    标签: python mysql python-2.7 pandas matplotlib


    【解决方案1】:

    文档对如何使用的解释有点简单 功能动画。不过有examples in the gallery和blog 教程,例如Jake Vanderplas'sSam Dolan's PDF

    这个来自 Jake Vanderplas 教程的例子可能是“Hello World” matplotlib 动画:

    from __future__ import division
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    
    def init():
        return [line]
    
    def animate(i, ax, line):
        x = np.linspace(0, 2*np.pi, N) + i/(N*2)
        ax.set_xlim(x.min(), x.max())
        line.set_data(x, np.sin(x))
        return [line]
    
    N = 100
    fig, ax = plt.subplots()
    line, = ax.plot([], [])
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    
    ani = animation.FuncAnimation(
        fig, animate, init_func=init, interval=0, frames=int(4*np.pi*N), 
        repeat=True, blit=True, fargs=[ax, line])
    plt.show()
    

    更改各种值或代码行,看看会发生什么。看看会发生什么 您将 return [line] 更改为其他内容。如果你学习和玩这些 例如,您可以了解这些部分是如何组合在一起的。

    一旦你理解了这个例子,你应该能够修改它以适应你的 目标。

    如果您遇到问题,请发布您的代码并描述错误消息或 你看到的不当行为。

    一些提示:

    • 既然动画需要调用line.set_data,我不认为你 可以使用 Pandas 的df.plot()。事实上,我不确定 Pandas DataFrame 是否是 在这里有用。将数据吸入列表或 NumPy 数组可能会更好 并将它们传递给line.set,如上所述,而不涉及 Pandas。

    • 打开与数据库的连接应该只进行一次。 animate 获取 叫了很多次。所以最好定义 conncquery -- 每次调用 animate 时不会改变的任何东西 -- 在animate 之外,并将它们作为参数传递回animate 通过 fargs参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 2011-05-10
      • 2013-10-29
      相关资源
      最近更新 更多