[英]Color bars in multi subplots doesn't follow the same scale
我正在嘗試比較四個二維直方圖。 我需要每個直方圖中的顏色條。 但是,很明顯,所有直方圖中的色標並不相同。 有沒有辦法讓這個比例相同?。
我使用的代碼在這里:
plt.set_cmap('hot')
fig = plt.figure()
fig.set_size_inches(10, 10)
# Adds subplot on position 1
ax = fig.add_subplot(221,aspect='equal')
# Adds subplot on position 2
ax2 = fig.add_subplot(222, aspect='equal')
ax3 = fig.add_subplot(223, aspect='equal')
ax4 = fig.add_subplot(224, aspect='equal')
h = ax.hist2d(data,datay,bins=(100,100), rasterized=True,range=np.array([(-7.9, 7.9), (-7.9, 7.9)]))
ax.set_title('step size = 2.0 ', size= 16, fontname='Comic Sans MS')
h2 = ax2.hist2d(data2,datay2,bins=(100,100), rasterized=True,range=np.array([(-7.9, 7.9), (-7.9, 7.9)]))
ax2.set_title('step size = 5.0 ', size= 16, fontname='Comic Sans MS')
h3 = ax3.hist2d(data3,datay3,bins=(100,100), rasterized=True,range=np.array([(-7.9, 7.9), (-7.9, 7.9)]))
ax3.set_title('step size = 6.0 ', size= 16, fontname='Comic Sans MS')
h4 = ax4.hist2d(data4,datay4,bins=(100,100), rasterized=True,range=np.array([(-7.9, 7.9), (-7.9, 7.9)]))
ax4.set_title('step size = 8.0 ', size= 16, fontname='Comic Sans MS')
"""
DEFINING COLOR BARS
"""
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(h[3], cax=cax)
divider = make_axes_locatable(ax2)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(h2[3], cax=cax)
divider = make_axes_locatable(ax3)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(h3[3], cax=cax)
divider = make_axes_locatable(ax4)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(h4[3], cax=cax)
ax2.set_yticks([])
ax4.set_yticks([])
plt.subplots_adjust(wspace=0.3)
plt.savefig('24pog.pdf')
plt.savefig('24pog.png')
plt.show()
您必須標准化顏色范圍(查看文檔中的cmax
、 cmin
。或者,您可以使用ScalarMappable
,即
import matplotlib.pyplot as plt, numpy as np
norm = plt.cm.colors.Normalize(vmin = 0, vmax = 2)
cmap = 'hot'
sc = plt.cm.ScalarMappable(norm = norm, cmap = cmap)
fig, ax = plt.subplots(2, 2)
for idx, axi in enumerate(ax.flat):
axi.hist2d(*np.random.rand(2, 10), cmap = cmap)
fig.colorbar(sc, ax = axi)
fig.show()
plt.hist2d
的問題是,要將相同的“顏色縮放”應用於您的四個數據實例,您必須事先知道四個直方圖的分箱值,但在繪制直方圖之前您不知道這些值。
一種可能的解決方案是繪制兩次直方圖,第二次您將了解所有分箱數據,但這似乎很浪費。
另一種方法是繪制四個直方圖,讀取分箱數據范圍,然后更改hist2d
返回的顏色網格的屬性,但這似乎很復雜。
在我看來,最簡單、最經濟的做法是自己模仿hist2d
,這里可以看到它的源碼(注意: self
是一個Axes實例)
def hist2d(self, x, y, bins=10, range=None, density=False, weights=None,
cmin=None, cmax=None, **kwargs):
...
h, xedges, yedges = np.histogram2d(x, y, bins=bins, range=range,
density=density, weights=weights)
...
pc = self.pcolormesh(xedges, yedges, h.T, **kwargs)
self.set_xlim(xedges[0], xedges[-1])
self.set_ylim(yedges[0], yedges[-1])
return h, xedges, yedges, pc
好吧,沒什么特別的……所以計划是在每個x, y
實例上調用histogram2d
,將結果保存在一個列表中,檢查分箱數據以找到正確的歸一化,最后,使用我們從histogram2d
保存的數據,調用pcolormesh
—請注意,如果需要,您還可以對所有繪圖使用相同的軸限制。
這是我使用過的代碼
In [49]: import matplotlib.pyplot as plt
...: from matplotlib.cm import ScalarMappable
...: from numpy.random import rand
...: from numpy import histogram2d
...:
...: # generate data - I have not your data…
...: data = ((rand(10000+500*i), rand(10000+500*i)) for i in range(4))
...:
...: # generate histograms (for you it's for x, y in ((x1,x2),(x2,y2),...)
...: hist = [histogram2d(x,y) for x, y in data]
...: # find min and max for each histogram
...: min_, max_ = zip(*((h.min(), h.max()) for h, xedges, yedges in hist))
...:
...: norm = plt.Normalize(min(min_), max(max_))
...: sm = ScalarMappable(norm, 'hot')
...:
...: fig, sp = plt.subplots(2, 2, constrained_layout=1)
...: sp = sp.flatten()
...: for ax, (h, xedges, yedges) in zip(sp, hist):
...: ax.pcolormesh(xedges, yedges, h.T, norm=norm, cmap='hot')
...: plt.colorbar(sm, ax=sp, aspect=30)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.