【问题标题】:How to create common colorbar, common labels and title in matplolib using subplots如何使用子图在 matplotlib 中创建公共颜色条、公共标签和标题
【发布时间】:2016-05-24 22:49:17
【问题描述】:

嘿,我正在尝试创建一个具有 4 个共享轴的子图的图形。我尝试了几个小时来获得沿 x 轴的常见水平颜色条的正确位置。我的代码的一个最小示例是:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 1 * np.pi, 400)
y = np.sin(x ** 2)
z = x+y

fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)

#print(axes.flat[1])

ax1=axes.flat[0]
ax2=axes.flat[1]
ax3=axes.flat[2]
ax4=axes.flat[3]


scatter = ax1.scatter(x, y, c=z)
ax2.scatter(x, y, c=z)
ax3.scatter(x, 2 * y ** 2 - 1, c=z)
ax4.scatter(x, 2 * y ** 2 - 1, c=z)


#-----------------------------------------#
ax1.set_xlim([0, 1])
ax1.set_ylim([0, 1])
ax2.set_xlim([0, 1])
ax2.set_ylim([0, 1])
ax3.set_xlim([0, 1])
ax3.set_ylim([0, 1])
ax4.set_xlim([0, 1])
ax4.set_ylim([0, 1])

ax1.set(aspect=1, adjustable='box-forced')
ax2.set(aspect=1, adjustable='box-forced')
ax3.set(aspect=1, adjustable='box-forced')
ax4.set(aspect=1, adjustable='box-forced')

ax1.set_ylabel('y')
ax3.set_xlabel('x')
ax3.set_ylabel('y')
ax4.set_xlabel('x')



plt.tight_layout()
cax,kw = mpl.colorbar.make_axes([ax for ax in axes.flat], orientation='horizontal')
plt.colorbar(scatter, cax=cax, **kw)
#-----------------------------------------#

fig.suptitle('Title', fontsize=20.00)

plt.show()

1) 我的主要问题:如何使颜色条的开头与 ax3 的 x 轴的左端对齐,而颜色条的末端与 ax4 的 x 轴的右边缘对齐?

2) 如何创建一个通用的 x-label 和 y-label,它们会自动居中?

提前致谢!

【问题讨论】:

    标签: python matplotlib scatter-plot subplot colorbar


    【解决方案1】:
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import AxesGrid
    import numpy as np
    import pylab
    # Simple data to display in various forms
    x = np.linspace(0, 1 * np.pi, 400)
    y = np.sin(x ** 2)
    z = x+y
    
    fig = plt.figure()
    
    grid = AxesGrid(fig, 111,  # similar to subplot(142)
                        nrows_ncols=(2, 2),
                        axes_pad=0.3,
                        share_all=True,
                        label_mode="L",
                        cbar_location="bottom",
                        cbar_mode="single",
                        )
    
    scatter = grid[0].scatter(x, y, c=z)
    grid[1].scatter(x, y, c=z)
    grid[2].scatter(x, 2 * y ** 2 - 1, c=z)
    grid[3].scatter(x, 2 * y ** 2 - 1, c=z)
    grid.cbar_axes[0].colorbar(scatter)
    pylab.figtext(.5, 0.15, 'x')
    pylab.figtext(.075, 0.55, 'y', rotation='vertical')
    for i in range(4):
        grid[i].set_xlim([0, 1])
        grid[i].set_ylim([0, 1])
    
    fig.suptitle('Title', fontsize=20.00)
    plt.show()
    

    这段代码的结果如下图所示

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-21
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      相关资源
      最近更新 更多