我正在尝试创建我的课程计划的pdf导出,并且我对图表使用plotly offline。在下面的MWE中,绘图将显示在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)发布于 2017-08-19 13:50:55
我认为因为plotly图形是svg对象并由javascript生成,所以我无法在jupyter笔记本上导出到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')发布于 2020-11-10 17:39:19
您需要指定适当的Default Renderer (或者渲染器,如果您想在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将执行magically know。
发布于 2020-01-28 17:55:23
一个更简单的解决方案是使用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)你可以阅读更多here
然后您可以使用File -> Download as -> PDF或终端jupyter nbconvert --to pdf <notebook_name>.ipynb对其进行转换
https://stackoverflow.com/questions/45761893
复制相似问题