簡體   English   中英

使用離線 plotly 圖將 jupyter 筆記本導出到 pdf; 缺少圖表

[英]Exporting jupyter notebook to pdf with offline plotly graph; missing graphs

我正在嘗試創建我的課程計划的 pdf 導出,並且我離線使用 plotly 來制作圖表。 在下面的 MWE 中,plot 將顯示在 Jupyter Notebook 中,但當我導出到 pdf 時不會顯示。我使用File-->Download as-->PDF via Latex (.pdf)

我想制作一個 pdf 而不是使用 html。我知道將 html 導出轉換為 pdf 可能需要額外的步驟,但我只是想知道是否有更直接的途徑(代碼修改?)我直接通過File-->Download as-->PDF via Latex (.pdf)

from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
init_notebook_mode(connected=True)
import plotly.graph_objs as go

data = [go.Scatter(
    x=[1, 2, 3],
    y=[3, 2, 1])
]
iplot(data)

我認為因為 plotly 圖形是 svg 對象並且由 javascript 生成,所以我沒有在我的 jupyter notebook 中導出到 PDF,所以我無法檢查和確認我的答案。

Plotly offline 沒有顯示為圖像,你可以使用 plotly online 來做到這一點,它可以免費生成圖形,

您需要創建一個在線帳戶,還需要粘貼來自 plotly 網站的用戶名和 API 密鑰(API 密鑰可以在設置中找到)。

注意:如果情節是公開或私人共享的,請仔細檢查,我對您的情節公開不承擔任何責任。

無論如何,這將為您提供圖形的圖像輸出,您可以將其導出為 PDF

代碼:

import plotly
import plotly.graph_objs as go

plotly.plotly.sign_in('<<username goes here>>', '<<api key goes here>>')
trace = go.Bar(x=[2, 4, 6], y= [10, 12, 15])
data = [trace]
layout = go.Layout(title='A Simple Plot', width=800, height=640)
fig = go.Figure(data=data, layout=layout)

plotly.plotly.image.save_as(fig, filename='a-simple-plot.png')

from IPython.display import Image
Image('a-simple-plot.png')

一個更簡單的解決方案是使用image_bytes = fig.to_image(format='png')而不是使用Image(image_bytes)顯示,但首先你應該安裝orca ,並且
pip3 install psutil requests
例子:

fig = go.Figure()
""" here goes some code to draw """

image_bytes = fig.to_image(format='png', , width=1200, height=700, scale=1) # you can use other formats as well (like 'svg','jpeg','pdf')

#instead of using fig.show()
from IPython.display import Image
Image(img_bytes)

你可以在這里閱讀更多

您可以使用File -> Download as -> PDF或使用終端jupyter nbconvert --to pdf <notebook_name>.ipynb

我沒有解決上述確切原始問題的解決方案。 但是,如果您想考慮 .html 格式,這里有一個對我有用的不錯的解決方案。 畢竟,我的目標只是與沒有安裝jupyter人共享筆記本。

使用plotlyhtmlexporter執行到.html的轉換。 這是您可以復制粘貼的一段代碼:

  pip install plotlyhtmlexporter
  jupyter nbconvert --to plotlyhtml mynotebook.ipynb

然后,您可能想嘗試將瀏覽器中的 .html 保存(打印)為 .pdf,但我認為這相當於將原始筆記本打印為 .pdf。 正如我所說,就我而言,擁有一個獨立於 jupyter 的 .html 文件就足夠了。

您需要指定適當的默認渲染器(或渲染器,如果您想在 Notebook 中將其可視化,以及在使用您提到的File-->Download as-->PDF via Latex (.pdf)選項導出為 PDF 時)。

我自己也為此苦苦掙扎了幾個小時,但最終對我有用的設置如下:

import plotly.io as pio
pio.renderers.default = "notebook+pdf"  # Renderer for Notebook and HTML exports + Renderer for PDF exports
# init_notebook_mode(connected=True)  # Do not include this line because it may not work

請注意,您可以使用+符號連接任意數量的渲染器,並且 Plotly 會神奇地知道何時使用它們中的每一個。

只需使用它並通過 HTML 將筆記本下載為 PDF。此外,您還需要 pip 先安裝 kaleido。

    import plotly.io as pio
    pio.kaleido.scope.default_format = "png"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM