我使用以下代碼在每個子圖的左上角添加一個顏色條。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
# 創建圖形5, 2)
# 為子圖指定網格的幾何形狀。
gs0 = gridspec.GridSpec(1, 3, wspace=0.7)
# 資料
a = np.range(3*5).reshape(3,5)
for ax_i in range(3)。
# 創建坐標軸。
ax = plt.subplot(gs0[ax_i])
# 繪制資料
plot_pcolor = plt.pcolormesh(a)
# ******** 繪制一個嵌套在繪圖內的色條********
# Define position of the desired colorbar in axes coordinate
# [(左下x,左下y),(右上x,右上y)]
ax_coord = [(0.05, 0.5), (0.2, 0.95) ]
# 把這兩個點從坐標軸轉換為顯示坐標。
tr1 = ax.transAxes.transform(ax_coord)
# 創建一個從顯示坐標到圖形坐標的逆向轉換# Position in figure coordinates [left, bottom, width, height]
datco = [tr2[0,0], tr2[0,1], tr2[1, 0]-tr2[0,0] 。tr2[1,1]-tr2[0,1] ]
#創建色條軸
cbar_ax = fig.add_axes(datco)
# plot colorbar
cbar = plt.colorbar(plot_pcolor, cax=cbar_ax)
# ********************************************************
if False:
plt.subplots_adjust(left=0.15, bottom=0.2, right=0.95, top=0.8)
plt.savefig('test.png', dpi=500)
然而,如果我使用subplots_adjust()函式(將上述代碼中的False替換為True),色條就不能正常移動。

你知道我怎樣才能處理它嗎?
uj5u.com熱心網友回復:使用inset_axes()模塊中的mpl_toolkits函式可以解決這個問題。也可以簡單地使用ax.inset_axes().
下面是新的代碼:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
# 創建圖形 # 創建圖形
fig = plt.figure(figsize=(5, 2)
# 為子圖指定網格的幾何形狀。
gs0 = gridspec.GridSpec(1, 3, wspace=0.7)
# 資料
a = np.range(3*5).reshape(3,5)
for ax_i in range(3)。
# 創建坐標軸。
ax = plt.subplot(gs0[ax_i])
# 繪制資料
plot_pcolor = plt.pcolormesh(a)
axins = inset_axes(ax, width="5%", height="50%", loc='upper left')
# plot colorbar
cbar = plt.colorbar(plot_pcolor, cax=axins)
# ********************************************************
if True:
plt.subplots_adjust(left=0.15, bottom=0.2, right=0.95, top=0.8)
plt.savefig('test.png', dpi=500)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/312393.html
標籤:


