2014-07-02 30 views
6

我想做類似於http://matplotlib.org/examples/pylab_examples/hist2d_log_demo.html的東西,但我讀過使用pylab代碼而不是python交互模式是不好的做法,所以我想用matplotlib.pyplot來做到這一點。但是,我無法弄清楚如何使用pyplot使這個代碼工作。使用,pylab,給出的例子是如何在matplotlib.pyplot中使用帶有hist2d的colorbar?

from matplotlib.colors import LogNorm 
from pylab import * 

#normal distribution center at x=0 and y=5 
x = randn(100000) 
y = randn(100000)+5 

hist2d(x, y, bins=40, norm=LogNorm()) 
colorbar() 
show() 

我已經嘗試了很多像

import matplotlib.pyplot as plt 
fig = plt.figure() 
ax1 = fig.add_subplot(1,1,1) 
h1 = ax1.hist2d([1,2],[3,4]) 

,從這裏我從plt.colorbar(h1)plt.colorbar(ax1)plt.colorbar(fig)ax.colorbar()等等等等都試過了,我不能讓任何工作。

一般來說,即使在閱讀http://matplotlib.org/faq/usage_faq.html之後,我仍然不太清楚pylab和pyplot之間的關係。例如pylab中的show()似乎在pyplot中變成plt.show(),但由於某種原因colorbar不會變成plt.colorbar()

例如,

+0

其實'colorbar'葉matplotlib本身:[鏈接](http://matplotlib.org/api/colorbar_api.html)。所以你可能需要''將mpl'和'mpl.colorbar()'導入matplotlib。 – arbulgazar

回答

3

這應做到:

from matplotlib.colors import LogNorm 
import matplotlib.pyplot as plt 
from numpy.random import randn 

#normal distribution center at x=0 and y=5 
x = randn(100000) 
y = randn(100000)+5 

H, xedges, yedges, img = plt.hist2d(x, y, norm=LogNorm()) 
extent = [yedges[0], yedges[-1], xedges[0], xedges[-1]] 
fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1) 
im = ax.imshow(H, cmap=plt.cm.jet, extent=extent, norm=LogNorm()) 
fig.colorbar(im, ax=ax) 
plt.show() 

注意彩條是如何連接到 「無花果」,而不是 「sub_plot」。這個here還有一些其他的例子。請注意,您還需要使用imshow生成ScalarMappable,如API here中所述。

+0

謝謝! 'imshow()'好像將數字視爲像素值?只是爲了測試,我使用x = [1,2,3]和y = [4,5,6],我不確定這是否正確,但我得到了非常平滑的彩虹圖像,儘管我使用的是微型數組,我無法弄清楚這些圖像的生成過程。我還得到了一個1-6的彩條,這對我來說很困惑?理想情況下,我希望顏色條比例與直方圖對齊,但也許它與imshow鏈接? – juesato

+0

'imshow'採用給定的MxN數組繪製並顯示相應的直方圖。我已經在我的答案中相應地修復了代碼。具體看我在說什麼,用你的例子的修改版本看'H',其中x = [1,2,3,3] y = [4,5,6,6]。如果你拿掉了'標準'的論點,你現在應該得到你要找的東西。如果你想離散輸出,有一個很好的例子[在這裏](http://stackoverflow.com/questions/14777066/matplotlib-discrete-colorbar)。還有其他一些很好的例子[這裏](http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut3.html)。 – philE

+0

請注意,'imshow'假設像您所說的那樣,每個值都是一個像素值,因此每個顏色的「框」與其他顏色框的大小相同。如果您需要設置不同的大小(例如在地圖投影中放置熱圖時),則應使用[pcolormesh](http://matplotlib.org/examples/pylab_examples/pcolor_demo.html)。 – mnky9800n

2

一個色條需要一個ScalarMappable對象作爲其第一個參數。 plt.hist2d將此返回爲返回元組的第四個元素。

h = hist2d(x, y, bins=40, norm=LogNorm()) 
colorbar(h[3]) 

完整代碼:

from matplotlib.colors import LogNorm 
import matplotlib.pyplot as plt 
import numpy as np 

#normal distribution center at x=0 and y=5 
x = np.random.randn(100000) 
y = np.random.randn(100000)+5 

h = plt.hist2d(x, y, bins=40, norm=LogNorm()) 
plt.colorbar(h[3]) 
show() 

enter image description here

相關問題