如何以 png 格式保存 Plotly 离线图?

How to save Plotly Offline graph in format png?

我正在离线使用 Plotly 在 python 中生成图表。

根据下面的文档,

https://plot.ly/python/offline/

这是我的代码,它完美地生成了 C:/tmp/test_plot.html 文件。

import plotly.offline as offline

offline.init_notebook_mode()

offline.plot({'data': [{'y': [4, 2, 3, 4]}], 
               'layout': {'title': 'Test Plot', 
                          'font': dict(family='Comic Sans MS', size=16)}},
             auto_open=False, filename='C:/tmp/test_plot')

如何将此图另存为 png 而不是 html?

offline.plot 方法有 image='pngimage_filename='image_file_name' 属性来将文件保存为 png

offline.plot({'data': [{'y': [4, 2, 3, 4]}], 
              'layout': {'title': 'Test Plot', 
                         'font': dict(family='Comic Sans MS', size=16)}},
             auto_open=True, image = 'png', image_filename='plot_image',
             output_type='file', image_width=800, image_height=600, 
             filename='temp-plot.html', validate=False)

offline.py 中或在线 plotly 查看更多详细信息。

但是,需要注意的是,由于输出图像绑定到 HTML,它将在浏览器中打开并请求保存图像文件的权限。您可以在浏览器设置中将其关闭。

或者, 您可能想使用 plot_mpl.
查看 plotly 到 matplotlib 的转换 以下示例来自 offline.py

from plotly.offline import init_notebook_mode, plot_mpl
    import matplotlib.pyplot as plt

    init_notebook_mode()

    fig = plt.figure()
    x = [10, 15, 20, 25, 30]
    y = [100, 250, 200, 150, 300]
    plt.plot(x, y, "o")

    plot_mpl(fig)
    # If you want to to download an image of the figure as well
    plot_mpl(fig, image='png')

您可以使 PhantomJS 自动保存与打开浏览器下载原始图像时宽度和高度完全相同的屏幕截图。

代码如下:

import plotly.offline as offline
from selenium import webdriver

offline.plot({'data': [{'y': [4, 2, 3, 4]}],
               'layout': {'title': 'Test Plot',
                          'font': dict(size=12)}},
             image='svg', auto_open=False, image_width=1000, image_height=500)

driver = webdriver.PhantomJS(executable_path="phantomjs.exe")
driver.set_window_size(1000, 500)
driver.get('temp-plot.html')
driver.save_screenshot('my_plot.png')

#Use this, if you want a to embed this .png in a HTML file
#bs_img = driver.get_screenshot_as_base64()

快速更新:从 plotly.py 3.2.0 开始,现在可以在完全离线的情况下以编程方式将图形导出为静态图像。

这是通过集成 orca project into plotly.py. Check out the announcement post 以获取更多详细信息来实现的。

import plotly
from html2image import Html2Image
import os

if not os.path.exists("./tmp"):
    os.mkdir("./tmp")

fig = dict(data = your_data, layout=your_layout)
plotly.offline.plot(fig, filename='./tmp/look.html',auto_open=False)

hti = Html2Image()
hti.output_path = './tmp/'
with open('tmp/look.html') as f:
    hti.screenshot(f.read(), save_as='ooo.png')