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

2023-09-06 07:04:39 作者:1糖果1加醋

I am using Plotly offline to generate graph in python.

As per the documentation below,

plotly保存为html所用参数,python Plotly绘图工具的简单使用

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

Here is my code, which perfectly generates C:/tmp/test_plot.html file.

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')

How can I save this graph as png instead of html?

解决方案

offline.plot method has image='png and image_filename='image_file_name' attributes to save the file as a 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)

See more details inside offline.py or online at plotly.

However, one caveat is that , since the output image is tied to HTML, it will open in browser and ask for permissions to save the image file. You can turn that off in your browser settings.

Alternately, You may want to look at plotly to matplotlib conversion using plot_mpl. Following example is from 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')