why matplotlib color bar do not show any tick marks and labels

3.3k views Asked by At

I've been trying to plot shape-file polygons with colors according to some data and add a color-bar. Below shown is the code that I've written for the purpose. It give the plot correctly, but there is no labels or tick marks for the color-bar.

fig, ax = plt.subplots(1,1,figsize=(12,10), subplot_kw={'projection': ccrs.PlateCarree()})
ptchs1   = []
for nshp in indx[0,:]:
    ptchs   = []
    pts     = np.array(shapes[nshp].points)
    pts     =pts[np.unique(np.where(~np.isnan(pts[:,:]))[0]),:]
    prt     = shapes[nshp].parts
    par     = list(prt) + [pts.shape[0]]
    for pij in xrange(len(prt)):
        ptchs.append(Polygon(pts[par[pij]:par[pij+1]]))
        ptchs1.append(Polygon(pts[par[pij]:par[pij+1]]))
    ind=np.where(indx==nshp)[1] ; 
    ax.add_collection(PatchCollection(ptchs,facecolor=my_cmap[np.where(indx==nshp)[1],:],edgecolor='k', linewidths=.5),ccrs.PlateCarree())
    plt.text(xtext[ind], ytext[ind],dnme[ind][0:7],fontsize=8,color='k',fontweight='bold', ha='center',va='center',transform=ccrs.Geodetic())
ax.set_xlim(np.round(mnbbx[0]).astype(int)-0.5,np.round(mxbbx[2]).astype(int)+0.5,2)
ax.set_ylim(np.round(mnbbx[1]).astype(int)-0.5,np.round(mxbbx[3]).astype(int)+0.5,2) 
m = cm.ScalarMappable(cmap=cmap)
m.set_array([])
m.set_clim(-0.5, 14+0.5) 
divider = make_axes_locatable(ax)
cax = divider.append_axes("right",aspect=20,size="5%",pad=0.05,map_projection=ccrs.PlateCarree())    
cb=fig.colorbar(m,cax=cax,norm=norm)
cb.set_ticks(np.arange(0,14))
cb.set_label('RainFall(mm/day)', rotation=90)   
cb.set_ticklabels([1,5,10,20,30,40,70,100,130,160,190,220,250])
xticks = np.arange(np.round(mnbbx[0]).astype(int)-0.5,np.round(mxbbx[2]).astype(int)+0.5,2)
yticks = np.arange(np.round(mnbbx[1]).astype(int)-0.5,np.round(mxbbx[3]).astype(int)+0.5,2)

gl = ax.gridlines(crs=ccrs.PlateCarree(),draw_labels=True,linewidth=0.7, color='black', alpha=1)
gl.xlabels_bottom = False ;     gl.ylabels_right = False
degree_locator = mticker.MaxNLocator(nbins=4) #it will give gridlines of 4*4 size
gl.xlocator = degree_locator
gl.ylocator = degree_locator
_DEGREE_SYMBOL = u'\u00B0'
gl.xformatter = LONGITUDE_FORMATTER #it will change lon to degree format
gl.yformatter = LATITUDE_FORMATTER
gl.ylabel_style = {'size': 12, 'color': 'black'} # here we can adjust color and size of ticks
gl.xlabel_style = {'color': 'black', 'size': 12 }
plt.show()

Can any one help me that why no color-bar tick mark and labels are not produced? enter image description here

I have updated my color bar plotting with this piece of code, it plots correctly, but the main plot and color bar size is different (either big or small)

    col_bnd=[0,1,   5,  10,  20,  30,  40,  70, 100, 130, 160, 190, 220, 250,300]
    norm = colors.BoundaryNorm(col_bnd, cmap.N)
    col_bnd=[1,   5,  10,  20,  30,  40,  70, 100, 130, 160, 190, 220, 250]
    ax1, ax2 = mpl.colorbar.make_axes(ax, shrink=0.68,aspect=20,pad=0.05)
    cbar = mpl.colorbar.ColorbarBase(ax1,    cmap=cmap,norm=norm,ticks=col_bnd,boundaries=None,format='%1i') #mpl.colors.Normalize(vmin=-0.5, vmax=1.5))
    cbar.set_clim(0, 300)
    cbar.set_label('RainFall(mm/day)', rotation=90)   

can anyone tell, how to make both main plot and color bar same size?

1

There are 1 answers

3
chicao On

[Edit]

As a commented below, it seems that colorbars need some different way of showing labels. You can try this:

cb.set_yticklabels([1,5,10,20,30,40,70,100,130,160,190,220,250])

You should call the 'legend' function for each artist you create at your code if you are doing other plottings. For instance, you have the ax artist and you set all the necessary info on it, except the legend. So you should call it before the plt.show() so it can generate the legend properly:

ax.legend()
fig.legend()

And so on.

The documentation has very good guides for the legend and artists function: