use*_*042 0 python jpeg matplotlib save ipython
我创建了一个函数,它从数据集中获取一系列值并输出一个图.例如:
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()
Run Code Online (Sandbox Code Playgroud)
所以我把这个函数称为如下: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
Run Code Online (Sandbox Code Playgroud)
调用此函数时,可以使用参考来保存图形:
fig = my_plot(...)
fig.savefig("somefile.png")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5812 次 |
| 最近记录: |