2017-08-04 81 views
0

我想顯示一個2D np.arrayimshow和相應的顏色條應該與np.array的直方圖共享其軸。這是一個嘗試,但是,沒有共享軸。matplotlib顏色條和共享軸直方圖

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib import cm 
from mpl_toolkits.axes_grid1 import make_axes_locatable 

fig, ax = plt.subplots(figsize=(7,10)) 

data = np.random.normal(0, 0.2, size=(100,100)) 
cax = ax.imshow(data, interpolation='nearest', cmap=cm.jet) 

divider = make_axes_locatable(plt.gca()) 
axBar = divider.append_axes("bottom", '5%', pad='7%') 
axHist = divider.append_axes("bottom", '30%', pad='7%') 

cbar = plt.colorbar(cax, cax=axBar, orientation='horizontal') 
axHist.hist(np.ndarray.flatten(data), bins=50) 

plt.show() 

我試圖使用在axHistsharex參數與axHist = divider.append_axes("bottom", '30%', pad='7%', sharex=axBar)但這不知何故移位直方圖數據:enter image description here

除了共享軸x,一個如何可以修改直方圖採取的顏色作爲相同的色彩地圖,類似於here

回答

2

您可以通過二進制數值,而不sharex顏色直方圖的每個補丁:

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib import cm 
from mpl_toolkits.axes_grid1 import make_axes_locatable 
from matplotlib.colors import Normalize 

fig, ax = plt.subplots(figsize=(7,10)) 

data = np.random.normal(0, 0.2, size=(100,100)) 
cax = ax.imshow(data, interpolation='nearest', cmap=cm.jet) 

divider = make_axes_locatable(plt.gca()) 
axBar = divider.append_axes("bottom", '5%', pad='7%') 
axHist = divider.append_axes("bottom", '30%', pad='7%') 

cbar = plt.colorbar(cax, cax=axBar, orientation='horizontal') 

# get hist data 
N, bins, patches = axHist.hist(np.ndarray.flatten(data), bins=50) 

norm = Normalize(bins.min(), bins.max()) 
# set a color for every bar (patch) according 
# to bin value from normalized min-max interval 
for bin, patch in zip(bins, patches): 
    color = cm.jet(norm(bin)) 
    patch.set_facecolor(color) 

plt.show() 

enter image description here

欲瞭解更多信息,尋找手冊頁:https://matplotlib.org/xkcd/examples/pylab_examples/hist_colormapped.html

+0

太好了!我通過在'N,bin,patches ...'行的下面添加'plt.xlim(data.min(),data.max())來解決共享軸的問題。'也許你也可以將它添加到答案中。 –

+0

您可以將您的變體發佈爲新答案。 – Serenity