保存由matplotlib python函数生成的绘图

2024-06-11 18:28:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个函数,从数据集中获取一系列值并输出一个绘图。例如:

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的情况下保存此图(这是因为我需要更改最小和最大温度参数)。


Tags: the函数plotmypltlocationmin温度
1条回答
网友
1楼 · 发布于 2024-06-11 18:28:25

将对某个变量的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")

相关问题 更多 >