【问题标题】:How to specify a directory in which to save an image using plotly py.image.save_as如何使用 plotly py.image.save_as 指定保存图像的目录
【发布时间】:2018-12-06 12:23:44
【问题描述】:

我想将生成的绘图图像保存到特定目录中,但 save_as 只有一个 filename 参数。 我正在使用以下代码来保存绘图

py.image.save_as(fig,filename='T_avg_'+lst_QoST_prop[i]+'.pdf')

有没有办法指定目录?

【问题讨论】:

  • 然后呢?你有什么问题?
  • 您是否尝试过使用filename 参数所在的路径?
  • @running.t 我想将 PDF 文件的输出保存到特定目录中。
  • @MoxieBall 是的,我有,它不起作用,它像参数中给出的那样重命名输出文件

标签: python pandas jupyter-notebook


【解决方案1】:

如果我对您的理解正确,您想使用 python 将图像保存在文件夹中。如果您搜索,该问题已经有了答案。

我使用的函数是

savefig()

例子:

plot = dtf.plot() 

fig = plot.get_figure() 

fig.savefig("output.png") or fig.savefig("output.pdf") ...

此外,您还必须导入 matplotlib 库:

import matplotlib.pyplot as plt

【讨论】:

  • 它没有用。请注意,我没有使用 matplotlib 来生成图表,我想继续使用 plotly
【解决方案2】:

为了将您的文件保存在特定的文件路径中,您需要使用filename 参数。

import plotly.plotly as py
help(py.image)
 |  Helper functions wrapped around plotly's static image generation api.
 |
 |  Class methods defined here:
 |  save_as(figure_or_data, filename, format=None, width=None, height=None, scale=None) from builtins.type
 |      Save a image of the plot described by `figure_or_data` locally as
 |      `filename`.
 |
 |      Valid image formats are 'png', 'svg', 'jpeg', and 'pdf'.
 |      The format is taken as the extension of the filename or as the
 |      supplied format.
 |
 |      positional arguments:
 |      - figure_or_data: The figure dict-like or data list-like object that
 |                        describes a plotly figure.
 |                        Same argument used in `py.plot`, `py.iplot`,
 |                        see https://plot.ly/python for examples
 |      - filename: The filepath to save the image to
 |      - format: 'png', 'svg', 'jpeg', 'pdf'
 |      - width: output width
 |      - height: output height
 |      - scale: Increase the resolution of the image by `scale` amount
 |             Only valid for PNG and JPEG images.


使用带路径的文件名(离线):

但是,这会导致在新标签页中打开的 HTML 文件 浏览器。图片保存在“下载”文件夹中,而不是 可以指定保存图片的路径。

from plotly.offline import py
from plotly.graph_objs import Scatter

plot([Scatter(x=[14, 19, 24, 29, 34, 39, 89],
              y=[30, 15, 18, 30, 24, 27, 50])], filename='2/billympoufo.html')

因此,您将在指定文件夹(下载文件夹中的图像)中拥有 html 文件,以绕过浏览器行为,您可以: (1)shutil 导入copyfile 并移动图像。

import os
import plotly
import plotly.graph_objs as go
import time
from shutil import copyfile

img_name = 'billympoufo'
dload = os.path.expanduser('~/Downloads')
save_dir = '/tmp'

data = [go.Scatter(x=[14, 19, 24, 29, 34, 39, 44, 49, 54, 59, 64, 69, 74, 79, 84, 89, 1], y=[30, 15, 18, 30, 24, 27, 50, 36, 39, 42, 50, 48, 51, 54])]

plotly.offline.plot(data, image_filename=img_name, image='svg')

### might need to wait for plot to download before copying
time.sleep(1)

copyfile('{}/{}.svg'.format(dload, img_name),
     '{}/{}.svg'.format(save_dir, img_name))

更多离线选项:(2)检查铬或(3)Firefox download behavior
通过使用参数auto_open=False它 应该将图像保存在文件夹中,而无需在您的 浏览器,但这是一个问题,
在此处查看:Directly save image (without opening in browser) #880
并且不打算这样做 那时添加此功能。
您也可以(4)使用 selenium 截取页面

在 Jupiter 中,对于离线保存,您可以执行以下操作:

import os
import pandas as pd
import plotly
import plotly.graph_objs as go
import time    
from selenium import webdriver
from PIL import Image
from pyvirtualdisplay import Display 

### from bokeh/io, slightly modified to avoid their import_required util
### didn't ultimately use, but leaving in case I figure out how to stick wtih phentomjs
### - https://github.com/bokeh/bokeh/blob/master/bokeh/io/export.py
def create_default_webdriver():
    '''Return phantomjs enabled webdriver'''
    phantomjs_path = detect_phantomjs()
    return webdriver.PhantomJS(executable_path=phantomjs_path, service_log_path=devnull)    

### based on last SO answer above
### - https://stackoverflow.com/questions/38615811/how-to-download-a-file-with-python-selenium-and-phantomjs
def create_chromedriver_webdriver(dload_path):
    display = Display(visible=0)
    display.start()
    chrome_options = webdriver.ChromeOptions()
    prefs = {"download.default_directory": dload_path}
    chrome_options.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(chrome_options=chrome_options)
    return driver, display
df = pd.DataFrame(
    {'fruits': ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'],
     'counts': [5, 3, 4, 2, 4, 6] })    
data = [go.Bar(x=df['fruits'],y=df['counts'])]    
dload = os.path.expanduser('~/Downloads')
html_file = 'plotly-fruit-plot.html'
fname = 'plotly-fruit-plot'

### original code contained height/width for the display and chromium webdriver
### I found they didn't matter; specifying the image size to generate will 
### produce a plot of that size no matter the webdriver
plotly.offline.plot(data, filename=html_file, auto_open=False,
                    image_width=1280, image_height=800,image_filename=fname, image='png')

### create webdrive, open file, maximize, and sleep
driver, display = create_chromedriver_webdriver(dload)    
driver.get('file:///{}'.format(os.path.abspath(html_file)))

# make sure we give the file time to download
time.sleep(1)

### was in the SO post and could be a more robust way to wait vs. just sleeping 1sec
# while not(glob.glob(os.path.join(dl_location, filename))):
#     time.sleep(1)    
driver.close()
display.stop()    
image = Image.open('{}.png'.format(os.path.join(dload, fname)))
image

(来源:jupiter


或在线文件夹:

import plotly.plotly as py
import plotly.graph_objs as go
# sign in
data = [
    go.Scatter(
        x=[14, 19, 24, 29, 5, 10, 22],
        y=[15, 18, 30, 24, 27, 30, 40]
    )
]

plot_out = py.plot(data, filename='all_my_graphs/my_new_plot')

【讨论】:

    【解决方案3】:

    我找到的最简单的方法,如有任何疑问,请按照文档https://plotly.com/python/static-image-export/

    安装前>> pip install -U kaleido

    import plotly.graph_objects as go
    import os
    
    fig = go.Figure()
    fig.add_trace(go.Bar(x=["A"],
                         y=[25],
                         marker_color='rgb(55, 83, 109)',
                         name="A"
                         ))
    fig.add_trace(go.Bar(x=["B"],
                         y=[50],
                         marker_color='rgb(26, 118, 255)',
                         name="B"
                         ))
    fig.update_layout(
        title='Test',
        xaxis_tickfont_size=14,
        yaxis=dict(
            title='Time (ms)',
            titlefont_size=16,
            tickfont_size=14,
        ),
        legend=dict(
            x=1.0,
            y=1.0,
            bgcolor='rgba(255, 255, 255, 0)',
            bordercolor='rgba(255, 255, 255, 0)'
        ),
        barmode='group',
        bargap=0.02,
        bargroupgap=0.6,
        width=500,
        height=400
    )
    
    #fig.show()
    
    if not os.path.exists("images"):
        os.mkdir("images")
    
    fig.write_image("images/fig1.pdf")
    

    【讨论】:

    • 相当多的代码与问题并不真正相关 - 您能否将其缩减为仅回答他们问题的部分,然后解释为什么会这样? :)
    猜你喜欢
    • 2015-10-04
    • 2022-01-04
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 2015-12-26
    • 2011-11-13
    • 2021-06-02
    相关资源
    最近更新 更多