python自动生成数字并保存到图片,保存由函数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.

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.

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

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

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. 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.

解决方案

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")

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值