[英]save a plot resulting from a function matplotlib python
我创建了一个函数,该函数从数据集中获取一定范围的值并输出绘图。 例如:
my_plot(location_dataset, min_temperature, max_temperature)
将返回函数中指定温度范围内的降水图。
假设我要保存该图,以保持加利福尼亚的温度在60-70F之间。 因此,我将我的函数my_plot(California, 60, 70)
,当温度在60至70F之间时,将获得加利福尼亚的降水图。
我的问题是:如何保存将函数调用为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
情况下保存该图(这是因为我需要更改最低和最高温度参数。
将对该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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.