可以通过在其自己的轴上添加colorbar来实现。 这可以通过手动创建一个附加轴并使用subplots_adjust()和add_axes()根据需要平移现有图来完成。
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(10, 6), dpi=300)
for i in range(1,7):
# This simply creates some random data to populate with
a = np.arange(10)
x, y = np.meshgrid(a, a)
z = np.random.randint(0, 7, (10, 10))
plt.subplot(2,3,i)
im = plt.contourf(x, y, z)
# Tight layout is optional
fig.tight_layout()
fig.subplots_adjust(right=0.825)
# [x1, x2,x3, x4],x1设置距离左边的距离,x2设置距离上部的距离,x3胖瘦,x4长短
cax = fig.add_axes([0.85, 0.075, 0.025, 0.82])
cbar = fig.colorbar(im, cax=cax)
cbar.set_ticks([0, 20, 40, 60, 80,100]) # 设置柱状图的标签刻度
cbar.set_ticklabels(['0', '20', '40', '60', '80',"100"]) # 设置柱状图的标签刻度值
cbar.ax.tick_params(labelsize=13) # 设置colorbar刻度字体大小
plt.show()
要删除图形间的轴标签,刻度线等,需要对上述方法进行一些不平凡的修改,其中plt.subplots()用于填充子图形对象的2x3数组,然后对其进行迭代。
import matplotlib.pyplot as plt
import numpy as np
nrows = 2
ncols = 3
# Create the subplot array
fig, (axes) = plt.subplots(nrows=nrows, ncols=ncols, figsize=(10, 6),
dpi=300, sharex=True, sharey=True)
for i in range(nrows):
for j in range(ncols):
a = np.arange(10)
x, y = np.meshgrid(a, a)
z = np.random.randint(0, 7, (10, 10))
im = axes[i][j].contourf(x, y, z)
# Remove the tick marks but leave the superleft and superbottom alone
if i != nrows-1:
if j != 0:
axes[i][j].tick_params(axis='both', which='both',
left=False, bottom=False, top=False)
else:
axes[i][j].tick_params(axis='both', which='both', bottom=False, top=False)
else:
if j != 0:
axes[i][j].tick_params(axis='both', which='both', left=False, top=False)
fig.tight_layout()
# Some additional whitespace adjustment is needed
fig.subplots_adjust(right=0.825, hspace=0.025, wspace=0.025)
# [x1, x2,x3, x4],x1设置距离左边的距离,x2设置距离上部的距离,x3胖瘦,x4长短
cax = fig.add_axes([0.85, 0.075, 0.025, 0.82])
cbar = fig.colorbar(im, cax=cax)
cbar.set_ticks([0, 20, 40, 60, 80,100]) # 设置柱状图的标签刻度
cbar.set_ticklabels(['0', '20', '40', '60', '80',"100"]) # 设置柱状图的标签刻度值
cbar.ax.tick_params(labelsize=13) # 设置colorbar刻度字体大小
plt.show()