Python - 在一个图中绘制两个图形

3
我有两个Python绘图函数:
def plotData(data):
    fig, ax = plt.subplots()
    results_accepted = data[data['accepted'] == 1]
    results_rejected = data[data['accepted'] == 0]
    ax.scatter(results_accepted['exam1'], results_accepted['exam2'], marker='+', c='b', s=40)
    ax.scatter(results_rejected['exam1'], results_rejected['exam2'], marker='o', c='r', s=30)
    ax.set_xlabel('Exam 1 score')
    ax.set_ylabel('Exam 2 score')
    return ax

第二个功能是:
def plot_boundry(theta,x):
    """
    """
    plt.figure(1)
    px = np.array([x[:, 1].min() - 2, x[:, 1].max() + 2])
    py = (-1 / theta[2]) * (theta[1] * px + theta[0])
    fig, ax = plt.subplots()
    ax.plot(px, py)
    return ax

我正在调用两个函数:

#####PLOT ######
ax = plotData(df)
ax = plot_boundry(opt_theta, x)

我得到了两个不同的图:
enter image description here enter image description here 我得到了两张不同的图片。如何将两个图合并成一张图?两个图应该合成一张图。

1
只需将从 plotData 返回的 ax 传递给 plot_boundary 并使用它来进行 plot。或者在函数外创建 ax,并将其传递给两个函数。 - AChampion
完成了什么之后,需要做什么?在哪里更改? - Amaresh
1
使用 ax 替代 fig, ax = plt.subplots() - AChampion
1个回答

2

这取决于您想要什么:

  1. 如果您希望两个图形重叠,那么可以在第一个图形后调用hold(True),然后绘制第二个图形,最后调用hold(False)

  2. 如果您希望将两个图形放在同一张图中,但是并排显示(或者上下显示),那么可以使用subplot。例如,在绘制第一个图形之前调用subplot(2, 1, 1),然后在绘制第二个图形之前调用subplot(2, 1, 2)


@Aman 不完全正确 - 你使用了 subplots,而不是 subplot。请注意,在 subplots 中,你好像缺少了一个 2 参数(http://matplotlib.org/examples/pylab_examples/subplots_demo.html)。 - Ami Tavory

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接