【问题标题】:Matplotlib animation in browser浏览器中的 Matplotlib 动画
【发布时间】:2018-11-25 21:27:01
【问题描述】:

我在尝试使用 mpld3 在浏览器中查看我的动画图表时遇到问题。关于我做错了什么的任何提示?如果我能弄清楚如何将其转换为 html 以便我可以将其嵌入到我的网站中,那就更好了。

import matplotlib.pyplot as plt
import mpld3
import matplotlib.animation as animation
from matplotlib import style
import pandas as pd
import matplotlib.dates
from mpldatacursor import datacursor

style.use('fivethirtyeight')

fig = plt.figure()
ax = plt.subplot2grid((1,1), (0,0))

dateparse = lambda x: pd.datetime.strptime(x, 
                                       '%m/%d/%y %I:%M:%S %p')
def animate (i):
    df = pd.read_csv('arp.csv', 
                     index_col='Number',
                     parse_dates=['Date'], 
                     date_parser=dateparse, 
                     delimiter =',')

    e = i+1440
    df_tfvolts = df.iloc[i:e, 1]
    df_tftime = df.iloc[i:e, 0]
    b = matplotlib.dates.date2num(df.iloc[i:e, 0])
    ax.clear()
    ax.plot(df_tftime, df_tfvolts, 'r')
    ax.fill_between(b, df_tfvolts, facecolor='r', alpha =0.3)

    for label in ax.xaxis.get_ticklabels():
        label.set_rotation(30)

    plt.title('Lghtbug 7')
    plt.subplots_adjust(top=0.893, 
                        bottom=0.2, 
                        right=0.962, 
                        left=0.11)

    plt.xlabel('Date')
    plt.ylabel('Volt')


    datacursor(hover=True, bbox = None, point_labels = None, 
               draggable = True)

ani = animation.FuncAnimation (fig, 
                               animate, 
                               interval=10)

mpld3.show()

【问题讨论】:

  • matplotlib 中的动画是一个 python 代码,它在画布上重复执行某些绘制事件。 mpld3 是一个库,它可以将 matplotlib 图形的子集转换为 html/javascript,以便在浏览器中显示。最终的 mpld3 图中没有任何 Python 代码,因为浏览器不理解 Python,而且您通常没有 Python 服务器来为您的网页提供服务。然而,动画需要 python 代码在客户端运行。因此,您需要在 mpld3 中编写动画(如果可能的话?)或以某种方式运行 python 服务器。

标签: python matplotlib mpld3


【解决方案1】:

我真的想做动画,可以看一下 Bokeh 库中的the surface3d example(代码是here)。

否则,如果您只想逐步查看数据中发生的情况,我建议您使用滑块。据说在 mpld3 中有一种方法可以做到这一点,但 demo 不起作用...您可以使用 Bokeh 检查 this other example

【讨论】:

  • mpld3 的演示仅适用于 Jupyter 笔记本(通过 HTML 显示)的上下文,其中后端 IPython.notebook.kernel 对象可在 Javascript 中访问。我认为 mpl3d 没有任何方法让 JS 元素(例如滑块)反馈给 python 代码。单击并拖动示例直接操作 Javascript 元素。在所有情况下,它似乎只是由 Python 代码生成的静态图,然后将其转换为通过 JS 修改的 HTML。
猜你喜欢
  • 2013-12-17
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
  • 2017-01-31
  • 1970-01-01
  • 2012-01-21
相关资源
最近更新 更多