问题描述
我正在使用带有 pandas 和 pandas-bokeh 的 Jupyter Notebook。
我可以创建图表没问题,但是当我想添加一个元素(如 Span)时,我不知道如何避免在笔记本中显示图表的第二个副本。
有没有办法做到这些:
- 延迟绘制图形,直到我准备好展示()它?
- 就地更新现有图形?
- 在绘制第二个图形之前删除现有图形?
此代码演示了该问题:
# spantest.ipynb
import pandas as pd
import numpy as np
import pandas_bokeh
from bokeh.models import Span
from bokeh.plotting import show
pandas_bokeh.output_notebook()
# Example linechart code from pandas-bokeh docs:
# https://github.com/PatrikHlobil/Pandas-bokeh#lineplot
np.random.seed(42)
df = pd.DataFrame({"Google": np.random.randn(1000)+0.2,"Apple": np.random.randn(1000)+0.17},index=pd.date_range('1/1/2000',periods=1000))
df = df.cumsum()
df = df + 50
fig = df.plot_bokeh(kind="line")
# So far,so good. At this point,I have one chart displayed.
# Now let's say I want to include a Span to indicate some threshold:
span = Span(location=150,dimension='width',line_color='green')
fig.add_layout(span)
show(fig)
# Now I can see the update,but it is displayed as a second copy of the chart. :-(
解决方法
找到答案 in the docs(想象一下)。
必须在图形创建行中添加选项 show_figure=False
以防止它在图形创建时显示:
fig = df.plot_bokeh(kind="line",show_figure=False)
然后当我调用 show(fig)
我可以发誓我在发布问题之前的某个时候尝试过。嗯嗯...