所以我有一个创建曲线的函数:
def make_plot(x, y, lab_x=None, lab_y=None, title=None, err_y=None,
interpolate_type='RBF', degree=None, smooth=True):
import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import Rbf, InterpolatedUnivariateSpline, CubicSpline, BarycentricInterpolator
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
x1 = np.linspace(min(x) * 0.9, max(x) * 1.1, 400)
fig, ax = plt.subplots(figsize=(15,10))
plt.xlabel(lab_x)
plt.ylabel(lab_y)
plt.grid(True)
ax.errorbar(x, y, fmt='.', yerr=err_y, color='r', label=u'Data')
if smooth:
X_plot = x1[:, np.newaxis]
flag_model = False
if interpolate_type == 'RBF':
smth = Rbf(x, y)
elif interpolate_type == 'IUS':
smth = InterpolatedUnivariateSpline(x, y)
elif interpolate_type == 'cubic':
smth = CubicSpline(x, y)
elif interpolate_type == 'polynomial':
if degree == None:
smth = BarycentricInterpolator(x, y)
else:
X = x[:, np.newaxis]
degree = int(degree)
import warnings
warnings.filterwarnings(action="ignore", module="scipy", message="^internal gelsd")
smth = make_pipeline(PolynomialFeatures(degree), LinearRegression())
smth.fit(X, y)
flag_model = True
else:
print 'Invalid interpolate type: You can choose RBF, IUS, cubic or polynomial'
return
if flag_model:
y1 = smth.predict(X_plot)
else:
y1 = smth(x1)
plt.plot(x1, y1, color='g', label=u'Smoth')
b1, a1, sig_b1, sig_a1 = leastsqr(x, y)
label_ = u'\nb={}±{} a={}±{}'.format(np.round(b1, 3), np.round(sig_b1, 3),
np.round(a1, 3), np.round(sig_a1, 3))
ax.set_title(title)
plt.plot(x1, b1 * x1 + a1, label=u'Linear' + label_)
plt.legend()
plt.show()
return fig, ax
实际上并不重要。我想要的就是多次应用此功能,并将所有输出图放在一个轴上。例如:
fig1, ax1 = make_plot(x1, y1)
fig2, ax2 = make_plot(x2, y2)
fig3 = plt.figure() # and put first and second plot to third figure
有可能吗?
答案 0 :(得分:0)
matplotlib批准编写绘图函数的方式 [需要引用] 是将对Axes
对象的引用传递给该函数,该对象将用于绘制您想要的任何图形,然后返回由您的函数创建的Artists
的列表
例如:
def my_plot(arg1, arg2, ax=None):
if ax is None:
ax = plt.gca()
ret = ax.plot(arg1, arg2) # replace with whatever you need here
return ret
fig, (ax1, ax2) = plt.subplots(1,2)
my_plot(x1,y1, ax=ax1)
my_plot(x2,y2, ax=ax2)