如何将绘图指定给变量,并将该变量用作Python函数中的返回值
我正在创建两个Python脚本,为技术报告生成一些绘图。在第一个脚本中,我定义了从硬盘上的原始数据生成绘图的函数。每个函数生成一种我需要的特定类型的绘图。第二个脚本更像是一个批处理文件,它应该围绕这些函数循环,并将生成的绘图存储在我的硬盘上 我需要的是一种用Python返回绘图的方法。所以基本上我想这样做:如何将绘图指定给变量,并将该变量用作Python函数中的返回值,python,matplotlib,plot,return-value,Python,Matplotlib,Plot,Return Value,我正在创建两个Python脚本,为技术报告生成一些绘图。在第一个脚本中,我定义了从硬盘上的原始数据生成绘图的函数。每个函数生成一种我需要的特定类型的绘图。第二个脚本更像是一个批处理文件,它应该围绕这些函数循环,并将生成的绘图存储在我的硬盘上 我需要的是一种用Python返回绘图的方法。所以基本上我想这样做: fig = some_function_that_returns_a_plot(args) fig.savefig('plot_name') 但我不知道的是如何使绘图成为我可以返回的变量。
fig = some_function_that_returns_a_plot(args)
fig.savefig('plot_name')
但我不知道的是如何使绘图成为我可以返回的变量。这可能吗?是这样吗?如何定义绘图功能
import numpy as np
import matplotlib.pyplot as plt
# an example graph type
def fig_barh(ylabels, xvalues, title=''):
# create a new figure
fig = plt.figure()
# plot to it
yvalues = 0.1 + np.arange(len(ylabels))
plt.barh(yvalues, xvalues, figure=fig)
yvalues += 0.4
plt.yticks(yvalues, ylabels, figure=fig)
if title:
plt.title(title, figure=fig)
# return it
return fig
然后像这样使用它们
from matplotlib.backends.backend_pdf import PdfPages
def write_pdf(fname, figures):
doc = PdfPages(fname)
for fig in figures:
fig.savefig(doc, format='pdf')
doc.close()
def main():
a = fig_barh(['a','b','c'], [1, 2, 3], 'Test #1')
b = fig_barh(['x','y','z'], [5, 3, 1], 'Test #2')
write_pdf('test.pdf', [a, b])
if __name__=="__main__":
main()
目前接受的答案对我来说并不适用,因为我使用了
scipy.stats.probplot()
进行绘图。我使用matplotlib.pyplot.gca()
直接访问:
"""
For my plotting ideas, see:
https://pythonfordatascience.org/independent-t-test-python/
For the dataset, see:
https://github.com/Opensourcefordatascience/Data-sets
"""
# Import modules.
from scipy import stats
import matplotlib.pyplot as plt
import pandas as pd
from tempfile import gettempdir
from os import path
from slugify import slugify
# Define plot func.
def get_plots(df):
# plt.figure(): Create a new P-P plot. If we're inside a loop, and want
# a new plot for every iteration, this is important!
plt.figure()
stats.probplot(diff, plot=plt)
plt.title('Sepal Width P-P Plot')
pp_p = plt.gca() # Assign an Axes instance of the plot.
# Plot histogram. This uses pandas.DataFrame.plot(), which returns
# an instance of the Axes directly.
hist_p = df.plot(kind = 'hist', title = 'Sepal Width Histogram Plot',
figure=plt.figure()) # Create a new plot again.
return pp_p, hist_p
# Import raw data.
df = pd.read_csv('https://raw.githubusercontent.com/'
'Opensourcefordatascience/Data-sets/master//Iris_Data.csv')
# Subset the dataset.
setosa = df[(df['species'] == 'Iris-setosa')]
setosa.reset_index(inplace= True)
versicolor = df[(df['species'] == 'Iris-versicolor')]
versicolor.reset_index(inplace= True)
# Calculate a variable for analysis.
diff = setosa['sepal_width'] - versicolor['sepal_width']
# Create plots, save each of them to a temp file, and show them afterwards.
# As they're just Axes instances, we need to call get_figure() at first.
for plot in get_plots(diff):
outfn = path.join(gettempdir(), slugify(plot.title.get_text()) + '.png')
print('Saving a plot to "' + outfn + '".')
plot.get_figure().savefig(outfn)
plot.get_figure().show()
如果您不想显示图片,而只想得到一个变量作为回报,那么您可以尝试以下操作(使用一些附加内容来删除axis): 返回的变量X可以与OpenCV一起使用,例如
cv2.imshow('',X)
这些进口必须包括:
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
一旦返回绘图,您计划如何使用它们?你想将每个文件保存为一个图像文件,即.png吗?是的,像png一样,但更具体地说,我会将它们保存为PDF格式。我看到了,可能是重复的。谢谢调用fig_bahr时,它将绘制图表。有没有办法生成图表而不显示?
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg