Han Zhengzu
Han Zhengzu

Reputation: 3852

Plotting shapefiles with its feature using matplotlib basemap

Here is my question.

Using:

fig = plt.figure(figsize =(8,6))
ax = plt.gca()
map =   Basemap(llcrnrlon=114.3,llcrnrlat=37.95,urcrnrlon=114.75,urcrnrlat=38.2)
map.readshapefile("xxx",'xxx',zorder =1,)
patches=[]
cs=plt.cm.Blues_r(np.arange(21)/21.)
for info, shape in zip(map.xxx_info, map.xxx):
    x,y=zip(*shape)
    patches.append( Polygon(np.array(shape), True) )  # facecolor= '#6582B3'
ax.add_collection(PatchCollection(patches, facecolor= cs,\
                  edgecolor='none', linewidths=1.5, zorder=2,alpha = 0.8))  

http://i13.tietuku.com/a331edcbeec29d5e.png

But when I want to depict some certain feature of these four different area(Example: population; GDP)

### for example
pop = [1000,1500,2000,500] ## corresponding to 4 polygons. 

How to set the facecolor for each polygon showing the relative population size.

In other way, the area where population was high has the darker blue as its facecolor, vice versa.

Update

My project has 22 polygon(uploaded here) and the corresponding features

 VALUE = np.array([6152.710436, 21077.95313, 1052.05006, 2891.89123, 5717.184961,      
        2431.608241, 502.12633, 28384.79976, 0., 73919.84013, 6242.307304,     
        1072.474419, 35222.73927, 146232.4488, 4703.720773, 4080.297812,
        22897.91752, 2683.5972,   472.840926,  3367.341526,16628.64741 ,114564.1283  ])    

norm = Normalize()
cmap = plt.get_cmap('Spectral_r')
norm = Normalize()

cs_set =pc.set_facecolor(cmap(norm(VALUE)))
ax.add_collection(pc)  

http://i11.tietuku.com/256bce12e2716163.png

My question is how to add a colorbar based on the VALUE?

I tried the method in the post I mentioned on the answer, but it doesn't work.

cb = colorbar_index(ncolors=len(VALUE),cmap=cmap, shrink=0.5, labels=VALUE)
cb.ax.tick_params(labelsize=6)

http://i11.tietuku.com/fbfd19949c4ceddd.png

The colorbar label of the figure above didn't fit with the truly data?

How to fix this problem? And is there an easier way to generate a colorbar?

Upvotes: 0

Views: 750

Answers (1)

Han Zhengzu
Han Zhengzu

Reputation: 3852

I have figured out one solution. Thanks for this post

If someone has more subtle way, please post here!

### original
for info, shape in zip(map.shiqu_info, map.shiqu):
    x,y=zip(*shape)
    patches.append( Polygon(np.array(shape), True) )  
pc = PatchCollection(patches, edgecolor='none', \    
                     linewidths=1.5, zorder=2,alpha = 0.8) 
## don't set facecolor here

## I add four sentences here!
cmap = plt.get_cmap('Blues')
norm = Normalize()
pop = np.array([1000,1500,2000,500])
pc.set_facecolor(cmap(norm(pop)))

ax.add_collection(pc)       

http://i11.tietuku.com/0a07095f88ba17ab.png

Upvotes: 0

Related Questions