如何使用子图

时间:2016-02-13 21:18:32

标签: python matplotlib scatter-plot subplot colorbar

嘿那里我正在尝试创建一个共享轴的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轴的右边缘对齐? / p>

2)如何创建一个自动居中的常用x-label和y-label?

提前致谢!

1 个答案:

答案 0 :(得分:0)

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()