在Matplotlib图表(HTML)中保存交互式系列

7

我有一个示例(来自matplotlib),其中包含一个交互式绘图,我可以从系列中选择要在绘图上显示的线条。这个方案完美地解决了我的问题,但现在我想将其导出到HTML中。我可以使用mpld3.save_html()成功地实现这一点,但是失去了系列选择方案的互动性。

以下是代码:

import numpy as np
import matplotlib.pyplot as plt, mpld3
from matplotlib.widgets import CheckButtons

t = np.arange(0.0, 2.0, 0.01)
s0 = np.sin(2*np.pi*t)
s1 = np.sin(4*np.pi*t)
s2 = np.sin(6*np.pi*t)

fig, ax = plt.subplots()
l0, = ax.plot(t, s0, visible=False, lw=2)
l1, = ax.plot(t, s1, lw=2)
l2, = ax.plot(t, s2, lw=2)
plt.subplots_adjust(left=0.2)

rax = plt.axes([0.05, 0.4, 0.1, 0.15])
check = CheckButtons(rax, ('2 Hz', '4 Hz', '6 Hz'), (False, True, True))

def func(label):
    if label == '2 Hz': l0.set_visible(not l0.get_visible())
    elif label == '4 Hz': l1.set_visible(not l1.get_visible())
    elif label == '6 Hz': l2.set_visible(not l2.get_visible())
    plt.draw()
check.on_clicked(func)

mpld3.save_html(fig, 'interactive_fig.html') #save to html here
plt.show()

有没有一种方法来保持这种交互性?

我也尝试过使用pickle保存,但仍然失去了系列的交互。

1个回答

8
无法在由mpld3生成的html文件中保持matplotlib.widget交互性。这是因为由mpld3生成的javascript在客户端运行,无法访问生成它的Python内核。您可以使用Static Interactive Widgets for IPython Notebooks方法,在html版本中实现类似于matplotlib的交互性。

1
谢谢您的评论。Python中是否还有其他模块可以生成这些交互式图形? - Michael Berry
也可以查看 bokeh 项目。 - Abraham D Flaxman
谢谢。我已经看了bokeh,但找不到任何交互式系列选择的内容。有什么建议吗? - Michael Berry
2
还可以查看plotly (https://plot.ly/python/)。当您将笔记本保存为HTML文件时,图表保持交互状态。 - mark jay
静态交互式小部件现在似乎已经过时,没有明显的继任者? - creanion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接