使用Matplotlib Python保存函数生成的图形

7
我创建了一个函数,它接受来自数据集的一系列值并输出一个图像。例如: my_plot(location_dataset, min_temperature, max_temperature)将返回指定温度范围内的降水量图像。
假设我想要保存60-70华氏度在加利福尼亚的温度下的降水图像。那么,我可以调用my_plot(California, 60, 70),并得到当温度在60到70华氏度之间时加利福尼亚的降水图像。
我的问题是:如何将调用函数后生成的图像保存为jpeg格式?
我知道plt.savefig()适用于非函数调用结果的情况,但在我的情况下,我该怎么做呢?
谢谢!
更多细节:以下是代码(大幅简化):
import matplotlib.pyplot as plt

def my_plot(location_dataset, min_temperature, max_temperature):
    condition = (location_dataset['temperature'] > min_temperature) & (dataset['temperature'] <= max_temperature)
    subset = location_dataset[condition] # subset the data based on the temperature range

    x = subset['precipitation'] # takes the precipitation column only
    plt.figure(figsize=(8, 6))
    plt.plot(x)
    plt.show()

那么,我按照以下方式调用此函数:my_plot(California, 60, 70),并获得了60-70温度范围的图表。如果我需要更改最小和最大温度参数,而不是在函数定义内部使用savefig,该如何保存这个图表呢?


因为我的图是我调用的函数的结果,这有意义吗,还是我应该编辑我的原始帖子? - user3495042
分享更多的代码。my_plot 函数返回什么?或者将图表保存在 my_plot 函数中。 - Andy
еҘҪзҡ„пјҢжҲ‘е·Із»Ҹзј–иҫ‘иҝҮдәҶгҖӮеӣһзӯ”дҪ зҡ„й—®йўҳпјҢmy_plotеҮҪж•°иҝ”еӣһдёҖдёӘж №жҚ®min_temperatureе’Ңmx_temperatureеҸӮж•°жҢҮе®ҡзҡ„жё©еәҰиҢғеӣҙз»ҳеҲ¶зҡ„еӣҫиЎЁгҖӮ - user3495042
在编写代码时,不应该在函数内部调用 pyplot,而是最好传递一个 Axes 对象给函数,并使用面向对象的接口。 - tacaswell
1个回答

23

将对figure的引用赋值给某个变量,并从您的函数中返回它:

import matplotlib.pyplot as plt

def my_plot(location_dataset, min_temperature, max_temperature):
    condition = (location_dataset['temperature'] > min_temperature) & (dataset['temperature'] <= max_temperature)
    subset = location_dataset[condition] # subset the data based on the temperature range

    x = subset['precipitation'] # takes the precipitation column only
    # N.B. referenca taken to fig
    fig = plt.figure(figsize=(8, 6))
    plt.plot(x)
    plt.show()

    return fig

当您调用此函数时,可以使用引用来保存图像:

fig = my_plot(...)
fig.savefig("somefile.png")

你试过直接将 fig.save 放入函数中吗? - Jason Goal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接