【问题标题】:Customizing subplots in matplotlib在 matplotlib 中自定义子图
【发布时间】:2018-06-30 04:36:31
【问题描述】:

我想使用子图放置 3 个图。第一行有两个图,一个会占据整个第二行。

我的代码在前两个图和下图之间创建了一个间隙。我该如何纠正?

df_CI
Country China   India
1980    5123    8880
1981    6682    8670
1982    3308    8147
1983    1863    7338
1984    1527    5704

fig = plt.figure() # create figure

ax0 = fig.add_subplot(221) # add subplot 1 (2 row, 2 columns, first plot)
ax1 = fig.add_subplot(222) # add subplot 2 (2 row, 2 columns, second plot). 
ax2 = fig.add_subplot(313) # a 3 digit number where the hundreds represent nrows, the tens represent ncols 
                            # and the units represent plot_number.

# Subplot 1: Box plot
df_CI.plot(kind='box', color='blue', vert=False, figsize=(20, 20), ax=ax0) # add to subplot 1
ax0.set_title('Box Plots of Immigrants from China and India (1980 - 2013)')
ax0.set_xlabel('Number of Immigrants')
ax0.set_ylabel('Countries')

# Subplot 2: Line plot
df_CI.plot(kind='line', figsize=(20, 20), ax=ax1) # add to subplot 2
ax1.set_title ('Line Plots of Immigrants from China and India (1980 - 2013)')
ax1.set_ylabel('Number of Immigrants')
ax1.set_xlabel('Years')

# Subplot 3: Box plot
df_CI.plot(kind='bar', figsize=(20, 20), ax=ax2) # add to subplot 1
ax0.set_title('Box Plots of Immigrants from China and India (1980 - 2013)')
ax0.set_xlabel('Number of Immigrants')
ax0.set_ylabel('Countries')

plt.show()

【问题讨论】:

    标签: matplotlib subplot


    【解决方案1】:

    我一直觉得子图语法有点难。 通过这些电话

    ax0 = fig.add_subplot(221)
    ax1 = fig.add_subplot(222)
    

    您将您的图形划分为 2x2 网格并填充第一行。

    ax2 = fig.add_subplot(313)
    

    现在你将它分成三行并填充最后一行。

    您基本上是在创建两个独立的子图网格,没有简单的方法来定义如何将子图从一个与另一个隔开。

    使用 gridspec 来创建一个更精细的网格并使用 python 切片解决它。

    fig = plt.figure()
    gs = mpl.gridspec.GridSpec(2, 2, wspace=0.25, hspace=0.25) # 2x2 grid
    ax0 = fig.add_subplot(gs[0, 0]) # first row, first col
    ax1 = fig.add_subplot(gs[0, 1]) # first row, second col
    ax2 = fig.add_subplot(gs[1, :]) # full second row
    

    现在您还可以使用wspacehspace 轻松调整间距。

    更复杂的布局也容易很多,只是熟悉的切片语法。

    fig = plt.figure()
    gs = mpl.gridspec.GridSpec(10, 10, wspace=0.25, hspace=0.25)    
    fig.add_subplot(gs[2:8, 2:8])
    fig.add_subplot(gs[0, :])
    for i in range(5):
        fig.add_subplot(gs[1, (i*2):(i*2+2)])
    fig.add_subplot(gs[2:, :2])
    fig.add_subplot(gs[8:, 2:4])
    fig.add_subplot(gs[8:, 4:9])
    fig.add_subplot(gs[2:8, 8])
    fig.add_subplot(gs[2:, 9])
    fig.add_subplot(gs[3:6, 3:6])
    
    # fancy colors
    cmap = mpl.cm.get_cmap("viridis")
    naxes = len(fig.axes)
    for i, ax in enumerate(fig.axes):
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_facecolor(cmap(float(i)/(naxes-1)))
    

    【讨论】:

    • 很好的答案!谢谢!
    猜你喜欢
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 2015-02-19
    • 2021-05-03
    • 2019-11-07
    • 1970-01-01
    • 2020-04-21
    相关资源
    最近更新 更多