2015-11-30 145 views
1

我有一個(H,ranges) = numpy.histogram2d()計算的結果,我試圖繪製它。Matplotlib:個性化imshow軸

鑑於H我可以很容易地把它放到plt.imshow(H)得到相應的圖像。 (見http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow

我的問題是所產生的圖像的軸線是H的「細胞計數」和是完全無關的ranges.

我知道可以使用關鍵字extent的值(如尖在:Change values on matplotlib imshow() graph axis)。但這種解決方案並不爲我工作:我的range值不是線性增長(實際上他們會呈指數級)

我的問題是:我怎麼可以把0​​的價值plt.imshow()?或者至少,還是我可以手動設置plt.imshow生成對象的標籤值?編號extent不是一個好的解決方案。

回答

1

您可以將刻度標籤更改爲更適合您數據的內容。

例如,在這裏我們將每5像素設定爲一個指數函數:

import numpy as np 
import matplotlib.pyplot as plt 

im = np.random.rand(21,21) 

fig,(ax1,ax2) = plt.subplots(1,2) 

ax1.imshow(im) 
ax2.imshow(im) 

# Where we want the ticks, in pixel locations 
ticks = np.linspace(0,20,5) 
# What those pixel locations correspond to in data coordinates. 
# Also set the float format here 
ticklabels = ["{:6.2f}".format(i) for i in np.exp(ticks/5)] 

ax2.set_xticks(ticks) 
ax2.set_xticklabels(ticklabels) 
ax2.set_yticks(ticks) 
ax2.set_yticklabels(ticklabels) 

plt.show() 

enter image description here

+0

超級!我在幾分鐘內實現了它,完成了這項工作! –

+0

這是非常危險的,因爲您已將數據值中的刻度標籤分離。 – tacaswell

1

imshow用於顯示圖像,所以它不支持x和y箱。 你既可以使用pcolor代替,

H,xedges,yedges = np.histogram2d() 
plt.pcolor(xedges,yedges,H) 

或使用plt.hist2d直接方式繪製直方圖。

2

擴展位上@thomas回答

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.image as mi 

im = np.random.rand(20, 20) 

ticks = np.exp(np.linspace(0, 10, 20)) 

fig, ax = plt.subplots() 

ax.pcolor(ticks, ticks, im, cmap='viridis') 
ax.set_yscale('log') 
ax.set_xscale('log') 

ax.set_xlim([1, np.exp(10)]) 
ax.set_ylim([1, np.exp(10)]) 

example result

通過讓mpl負責非線性映射您現在可以準確地重疊其他藝術家。這有一個性能打擊(因爲pcolorAxesImage更昂貴),但獲得準確的蜱是值得的。