[英]save a plot resulting from a function 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)
will return a plot of precipitation for the range of temperature specified in the function. my_plot(location_dataset, min_temperature, max_temperature)
将返回函数中指定温度范围内的降水图。
Let's say I want to save the plot for the temperature between 60-70F in California. 假设我要保存该图,以保持加利福尼亚的温度在60-70F之间。 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. 因此,我将我的函数
my_plot(California, 60, 70)
,当温度在60至70F之间时,将获得加利福尼亚的降水图。
My question is: how do I save a plot that results from calling a function into a jpeg format? 我的问题是:如何保存将函数调用为jpeg格式的绘图?
I know of plt.savefig()
when it is not the result of calling a function but in my case how do I do this? 我知道
plt.savefig()
不是调用函数的结果,但是在我的情况下我该怎么做?
Thanks! 谢谢!
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()
So then I call this function as follow: my_plot(California, 60, 70)
and I get my plot for the 60-70 temperature range. 因此,我按如下方式调用此函数:
my_plot(California, 60, 70)
然后得到60-70温度范围的图。 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. 如何在没有函数定义内包含
savefig
情况下保存该图(这是因为我需要更改最低和最高温度参数。
Take the reference to the figure
to some variable, and return it from your function: 将对该
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
When you call this function, you can use the reference for saving the figure: 调用此函数时,可以使用参考来保存图形:
fig = my_plot(...)
fig.savefig("somefile.png")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.