JupyterLab 图不显示。它显示空白结果(但在 jupyter notebook 上工作正常)

JupyterLab fig does not show. It shows blank result (but works fine on jupyternotebook)

我是 JupyterLab 的新手,正在努力学习。

当我尝试绘制图表时,它在 jupyter notebook 上工作正常,但在 jupyterlab 上不显示结果。谁能帮我解决这个问题?

代码如下:

import pandas as pd
import pandas_datareader.data as web
import time
# import matplotlib.pyplot as plt
import datetime as dt
import plotly.graph_objects as go
import numpy as np
from matplotlib import style
# from matplotlib.widgets import EllipseSelector
from alpha_vantage.timeseries import TimeSeries

下面是绘图代码:

def candlestick(df):
    fig = go.Figure(data = [go.Candlestick(x = df["Date"], open = df["Open"], high = df["High"], low = df["Low"], close = df["Close"])])
    fig.show()

JupyterLab 结果: Link to the image (JupyterLab)

JupyterNotebook 结果: Link to the image (Jupyter Notebook)

我已经将 JupyterLab 和 Notebook 更新到最新版本。我不知道是什么导致 JupyterLab 停止显示图形。

感谢您阅读我的 post。将不胜感激。

注*

我没有包括数据读取部分(库存 OHLC 值)。它包含 API 键。很抱歉给您带来不便。 另外,这是我第二次 post 堆栈溢出。如果这不是一个写得好的post,我很抱歉。如果可能的话,我会尝试付出更多的努力。再次感谢您的帮助。

TL;DR:

运行 执行以下操作然后重启你的 jupyter lab

jupyter labextension install @jupyterlab/plotly-extension

开始实验:

jupyter lab

使用以下代码进行测试:

import plotly.graph_objects as go
from alpha_vantage.timeseries import TimeSeries

def candlestick(df):
    fig = go.Figure(data = [go.Candlestick(x = df.index, open = df["1. open"], high = df["2. high"], low = df["3. low"], close = df["4. close"])])
    fig.show()

# preferable to save your key as an environment variable....
key = # key here

ts = TimeSeries(key = key, output_format = "pandas")
data_av_hist, meta_data_av_hist = ts.get_daily('AAPL')

candlestick(data_av_hist)

Note: Depending on system and installation of JupyterLab versus bare Jupyter, jlab may work instead of jupyter

更长的解释:

由于此问题与 plotly 而不是 matplotlib 有关,因此您不必使用以下的“内联魔法”:

%matplotlib inline

每个扩展都必须安装到 jupyter lab,你可以看到列表:

jupyter labextension list

关于另一个扩展的更详细的解释,请参见相关问题:

.

但是,扩展可能不支持当前的 JupyterLab,并且由于各种原因可能无法更新 JupyterLab:

ValueError: The extension "@jupyterlab/plotly-extension" does not yet support the current version of JupyterLab.

在这种情况下,一个快速的解决方法是保存图像并再次显示:

from IPython.display import Image

fig.write_image("image.png")
Image(filename='image.png')

要使 Plotly 的 write_image() 方法起作用,必须安装 kaleido

pip install -U kaleido

这是一个完整示例(最初来自 Plotly),用于测试此解决方法:

import os
import pandas as pd
import plotly.express as px

from IPython.display import Image

df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"),
    dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Resource="Alex"),
    dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30', Resource="Max")
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Resource", color="Resource")

if not os.path.exists("images"):
    os.mkdir("images")

fig.write_image("images/fig1.png")
Image(filename='images/fig1.png')