将绘图对象添加到图中的轴

时间:2020-09-01 14:43:49

标签: matplotlib

我正在尝试在图形中添加图形,如下所示:

fig, axs = plt.subplots(1,2, figsize =(10,5))
plot1 = customized_function(x1, y1) # any plot object
plot2 = customized_function(x2, y2) # any plot object
axs[0] = plot1 # adding the plot1 to the figure
axs[1] = plot2 # adding the plot2 to the figure

但是我找不到将plot1plot2添加到图中的方法。我一直在寻找解决方案,但该解决方案无法满足我的需求。我找到的解决方案是这样:

fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Axes values are scaled individually by default')
ax1.plot(x, y)
ax2.plot(x + 1, -y)

但是,我要添加的图已经完成了。

有什么建议吗?

可复制的代码:

from sklearn.metrics import roc_curve
def customized_function(y_train, prob_train):
    fpr = dict()
    tpr = dict()

    fpr, tpr, _ = roc_curve(y_train, prob_train)
    roc_auc = dict()
    roc_auc = auc(fpr, tpr)

    # make the plot
    plt.figure(figsize=(10, 10))
    plt.plot(fpr, tpr)
    plt.title('ROC curve and AUC')
    plt.show()
    

y_train = np.array([0,0,0,0,0,1,1,1,0,1])
prob_train = np.array([0.1,0.2,0.3,0.4,0.5,0.1,0.1,0.8,0.9,1])

y_test = np.array([0,1,1,0,0,0,1,0,0,1])
prob_test = np.array([0.1,0.4,0.2,0.5,0.1,0.1,0.2,0.8,0.3,0.1])

customized_function(y_train, prob_train)
customized_function(y_test, prob_test)

1 个答案:

答案 0 :(得分:0)

推荐的绘制绘图功能的方法是将对轴的引用传递给该功能:

def function_customized_plot(x, y, ax=None):
    if ax is None:
        ax = plt.gca()
    (...) # rest of your code here

fig, axs = plt.subplots(1,2, figsize =(10,5))
function_customized_plot(x1, y1, ax=axs[0])
function_customized_plot(x2, y2n ax=axs[1])
相关问题