[英]Is there a way to plot Matplotlib's Imshow against changing x-axis limits and y-axis limits?
[英]Matplotlib: personalize imshow axis
我有一個(H,ranges) = numpy.histogram2d()
計算的結果,我試圖繪制它。
給定H
我可以輕松地將其放入plt.imshow(H)
以獲得相應的圖像。 (見http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow )
我的問題是產生的圖像的軸是H
的“細胞計數”並且與ranges.
的值完全無關ranges.
我知道我可以使用關鍵字extent
(如下所示: 在matplotlib imshow()圖軸上更改值 )。 但是這個解決方案對我不起作用:我的range
值不會線性增長(實際上它們呈指數級增長)
我的問題是:如何將range
的值放在plt.imshow()
? 或者至少,或者我可以手動設置plt.imshow
結果對象的標簽值嗎?
編輯extent
不是一個好的解決方案。
在@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)])
通過讓mpl處理非線性映射,您現在可以准確地過度繪制其他藝術家。 對此有一個性能影響(因為pcolor
比AxesImage
更昂貴),但獲得准確的滴答是值得的。
imshow
用於顯示圖像,因此它不支持x和y bin。 你可以使用pcolor
代替,
H,xedges,yedges = np.histogram2d()
plt.pcolor(xedges,yedges,H)
或使用直接繪制直方圖的plt.hist2d
。
您只需將刻度標簽更改為更適合您數據的標簽即可。
例如,這里我們將每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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.