繁体   English   中英

Jupyter Notebook 中的 Plotly 图消失了吗?

[英]Disappearing Plotly plots in Jupyter Notebook?

我在 Python 中使用 Plotly 在 Jupyter Notebook 中创建了一些图,不幸的是,每次我打开 Jupyter Notebook 时,我都必须重新加载数据才能在 Plotly 中看到这些图,为什么会发生这种情况,如果我能以某种方式让这些图自己生成运行 Jupyter Notebook 的时间? 请给我一些建议,这对我来说真的是个大问题。

例如像这样的代码,当我打开它时,我必须重新加载数据集才能在 Jupyter Notebook 中再次显示它:

#Size of the plot
figsize=(10,5)

#Count of values of good and bad credits in the dataset
goodCount = data[data["Risk"]== 'good']["Risk"].value_counts().values
badCount = data[data["Risk"]== 'bad']["Risk"].value_counts().values

#Bar fo good credit
trace0 = go.Bar(x = data[data["Risk"]== 'good']["Risk"].value_counts().index.values,
               y = data[data["Risk"]== 'good']["Risk"].value_counts().values,
               name='Good credit',
               text= goodCount, 
               textposition="auto", 
               marker = dict(color = "green", line=dict(color="black", width=1),),opacity=1)

#Bar of bad credit
trace1 = go.Bar(x = data[data["Risk"]== 'bad']["Risk"].value_counts().index.values,
               y = data[data["Risk"]== 'bad']["Risk"].value_counts().values,
               name='Bad credit', 
               text= badCount, 
               textposition="auto", 
               marker = dict(color = "red", line=dict(color="black", width=1),),opacity=1)

#Creation of bar plot 
data = [trace0, trace1]
layout = go.Layout()
layout = go.Layout(yaxis=dict(title='Count'),
                   xaxis=dict(title='Risk variable'),
                   title='Distribution of target variable in the dataset')


fig = go.Figure(data=data, layout=layout)
fig.show()

故障排除指南建议运行“重新启动并清除输出”菜单命令,或者随时在任何单元格中执行此块以在事情不同步时恢复数字:

import plotly.io as pio
pio.renderers.default='notebook'

您看到的是 Plotly Notebook 集成的限制,如果您可以升级到 JupyterLab,效果会更好:)

其实我也有同样的问题。 您应该确保在保存笔记本时将其标记为“受信任”,您应该会在笔记本的右上角或“文件”菜单中看到一个小框。 如果它没有被标记为这样,只需单击它(确保它是可信的,因为任何应该在笔记本打开时运行的代码,例如绘图图形,都将被执行)。

我可以添加到@nicolaskruchten 的答案中:

此处记录的原因:

注意:默认渲染器在单个 session 的持续时间内持续存在,但它们不会跨会话持续存在。 如果您在 IPython kernel 中工作,这意味着默认渲染器将在 kernel 的生命周期内持续存在,但它们不会在 kernel 重新启动后持续存在。

故障排除文档“JupyterLab 问题”部分所示,您有两种解决问题的选择:

  1. 调用fig.show("notebook")而不仅仅是fig.show() (最简单的)
  2. 如果此问题反复出现,您可以使用以下方法:
 import plotly.io as pio pio.renderers.default='notebook'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM