保存由函数matplotlib python生成的图 [英] save a plot resulting from a function matplotlib python

查看:127
本文介绍了保存由函数matplotlib python生成的图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created a function that takes a range of values from a data set and outputs a plot. For instance:

my_plot(location_dataset, min_temperature, max_temperature)将返回函数中指定温度范围内的降水图.

my_plot(location_dataset, min_temperature, max_temperature) will return a plot of precipitation for the range of temperature specified in the function.

比方说,我想保存在加利福尼亚60-70F之间的温度曲线图.因此,我将调用函数my_plot(California, 60, 70)并获得温度在60至70F之间的加利福尼亚降水图.

Let's say I want to save the plot for the temperature between 60-70F in California. so, I would call my function my_plot(California, 60, 70) and will get a plot of precipitation for California when temperatures are between 60 and 70F.

我的问题是:如何保存将函数调用为jpeg格式的图?

My question is: how do I save a plot that results from calling a function into a jpeg format?

我知道plt.savefig()不是由调用函数引起的,但就我而言,我该怎么做?

I know of plt.savefig() when it is not the result of calling a function but in my case how do I do this?

谢谢!

更多详细信息:这是我的代码(经过简化):

More details: here is my code (heavily simplified):

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放在函数定义内的情况下保存该图(这是因为我需要更改最低和最高温度参数.

So then I call this function as follow: my_plot(California, 60, 70) and I get my plot for the 60-70 temperature range. how do I save this plot without having the savefig inside the function definition (and that is because I need to change the min and max temperature parameters.

推荐答案

将对figure的引用带到某个变量,然后从您的函数中返回它:

Take the reference to the figure to some variable, and return it from your function:

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

调用此函数时,可以使用参考来保存图形:

When you call this function, you can use the reference for saving the figure:

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

这篇关于保存由函数matplotlib python生成的图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆