2016-03-08 505 views
1

我借鑑cartopy國家,並從彩色圖添加顏色如下:Matplotlib:添加顏色條到cartopy圖像

cmap = plt.get_cmap('viridis') 
norm = matplotlib.colors.Normalize(vmin=dfSingle.min(), vmax=dfSingle.max()) 

dfSingle[:] = norm(dfSingle).data 


kw = dict(resolution='110m', category='cultural', 
      name='admin_0_countries') 
states_shp = shapereader.natural_earth(**kw) 
shp = shapereader.Reader(states_shp) 

ax = plt.axes(projection=ccrs.PlateCarree()) 

for record, state in zip(shp.records(), shp.geometries()): 
    try: 
     colorNormalized = dfSingle[int(record.attributes['iso_n3'])] 

     ax.add_geometries([state], ccrs.PlateCarree(), 
        facecolor=cmap(colorNormalized), edgecolor='black') 
    except KeyError: 
     ax.add_geometries([state], ccrs.PlateCarree(), 
      facecolor='grey', edgecolor='black') 

,我的數據是這樣的:

In [246]: dfSingle.head() 
Out[246]: 
V2 
12 0.179909 
31 0.332297 
32 0.642179 
36 0.815429 
48 0.215383 

現在我想添加對應於規範化值的顏色條和cmap。不過,我不斷收到錯誤:

ax.get_figure().colorbar() 
AttributeError: 'GeoAxesSubplot' object has no attribute 'colorbar' 

cmap.colorbar 
AttributeError: 'ListedColormap' object has no attribute 'colorbar' 

foo = matplotlib.cm.ScalarMappable(cmap) 
ax.get_figure().colorbar(foo) 
TypeError: You must first set_array for mappable 

foo.set_array(dfSingle.values) 
ax.get_figure().colorbar(foo) 
AttributeError: 'ListedColormap' object has no attribute 'autoscale_None' 

這是我的陰謀的外觀現在:

image without colorbar

我如何可以添加顏色條?

+0

這不就是一個matplotlib問題嗎? http://stackoverflow.com/a/11558629/741316 – pelson

+0

@pelson第一部分是一個'cartopy'問題:當axis是一個'GeoAxesSubplot'時,'ax.get_figure()。colorbar()'不起作用。 cartopy。 'ax.colorbar()'也沒有。這將是偉大的,如果它的工作和[顏色軸軸得到正確的高度](http://stackoverflow.com/questions/30030328/correct-placement-of-colorbar-relative-to-geo-axes-cartopy)。但是,只要不改變,'plt.colorbar(sm,cax = ax)'應該可以工作。 – j08lue

回答

0

解決方法是設置_A = [],而不是使用set_array()函數。

sm = plt.cm.ScalarMappable(cmap=cmap) 
sm._A = [] 
cb = plt.colorbar(sm) 
cb.set_ticks([])