【问题标题】:How can I plot multiple figure in the same line with matplotlib?如何使用 matplotlib 在同一行中绘制多个图形?
【发布时间】:2015-12-15 14:05:10
【问题描述】:

在我的Ipython Notebook 中,我有一个脚本会生成一系列多个数字,如下所示:

问题是,这些数字take too much space,而我正在制作许多这样的组合。这让我很难在这些数字之间导航。

我想在同一行中制作一些情节。我该怎么做?

更新:

感谢 fjarri 的建议,我已经更改了代码,这适用于在同一行中绘制。

现在,我想让它们绘制在不同的行中(默认选项)。我该怎么办?我尝试了一些,但不确定这是否正确。

def custom_plot1(ax = None):
    if ax is None:
        fig, ax = plt.subplots()
    x1 = np.linspace(0.0, 5.0)
    y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
    ax.plot(x1, y1, 'ko-')
    ax.set_xlabel('time (s)')
    ax.set_ylabel('Damped oscillation')

def custom_plot2(ax = None):
    if ax is None:
        fig, ax = plt.subplots()
    x2 = np.linspace(0.0, 2.0)
    y2 = np.cos(2 * np.pi * x2)
    ax.plot(x2, y2, 'r.-')
    ax.set_xlabel('time (s)')
    ax.set_ylabel('Undamped')

# 1. Plot in same line, this would work
fig = plt.figure(figsize = (15,8))
ax1 = fig.add_subplot(1,2,1, projection = '3d')
custom_plot1(ax1)
ax2 = fig.add_subplot(1,2,2)
custom_plot2(ax2)

# 2. Plot in different line, default option
custom_plot1()
custom_plot2()

【问题讨论】:

    标签: python matplotlib ipython-notebook


    【解决方案1】:

    只使用子图。

    plt.plot(data1)
    plt.show()
    plt.subplot(1,2,1)
    plt.plot(data2)
    plt.subplot(1,2,2)
    plt.plot(data3)
    plt.show()
    

    (这段代码不应该工作,重要的是它背后的想法)

    对于数字 2,同样的事情:使用子图:

    # 1. Plot in same line, this would work
    fig = plt.figure(figsize = (15,8))
    ax1 = fig.add_subplot(1,2,1, projection = '3d')
    custom_plot1(ax1)
    ax2 = fig.add_subplot(1,2,2)
    custom_plot2(ax2)
    
    # 2. Plot in same line, on two rows
    fig = plt.figure(figsize = (8,15))                  # Changed the size of the figure, just aesthetic
    ax1 = fig.add_subplot(2,1,1, projection = '3d')     # Change the subplot arguments
    custom_plot1(ax1)
    ax2 = fig.add_subplot(2,1,2)                        # Change the subplot arguments
    custom_plot2(ax2)
    

    这不会显示两个不同的数字(这是我从“不同行”中理解的),而是将两个数字放在一个数字中,一个在另一个之上。

    现在,解释子情节参数:subplot(rows, cols, axnum) rows 将是图形划分的行数。 cols 将是图形划分的列数。 axnum 将是您要绘制的分区。

    在你的情况下,如果你想要两个并排的图形,那么你想要一行两列 --> subplot(1,2,...)

    在第二种情况下,如果你想要两个图形一个在另一个之上,那么你想要 2 行和 1 列 --> subplot(2,1,...)

    对于更复杂的分布,使用gridspechttp://matplotlib.org/users/gridspec.html

    【讨论】:

    • 太棒了。但是我正在使用自定义绘图功能,我应该让函数返回什么?将其与plt.plot()subplot() 结合使用?查看我的更新。
    • 也许你应该使用无状态API,即创建图形为fig = plt.figure(),子图为s = fig.add_subplot(1,2,1),然后将s传递给你的函数,这些函数将在那里绘制而不关心它是否是子情节与否。
    • 与@fjarri 相同。将参数传递给您的函数。
    • @fjarri,对不起,无状态 API 是什么意思?有什么可以看的例子吗?
    • 我几乎在我的评论中解释了它。调用 plt.plot() 在幕后创建一个图形和一个 Axes 对象;使用plt.figure()add_subplot(),您可以控制这些对象并将它们传递给函数。 matplotlib 库中的大多数示例混合了这两个 API,这使得事情变得非常不清楚。参见例如this tutorial 了解更多详情。
    猜你喜欢
    • 1970-01-01
    • 2014-04-12
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 2017-01-29
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多