Cebbie
Cebbie

Reputation: 1889

Matplotlib- Any way to use integers AND decimals in colorbar ticks?

The issue

I have a plot and I need the colorbar ticks to be larger since I'm adding this plot to a multi-panel plot & the tick labels will be hard to read otherwise with everything so condensed. My problem is that if I make the labels bigger, they start running into each other near the end of the colorbar because of the .0 decimals. I can't make all the ticks integers though since I need the decimal labels near the left side & center of the colorbar.

enter image description here

The code

Here's the code I used to make the plot.

#Set variables
lonlabels = ['0','45E','90E','135E','180','135W','90W','45W','0']
latlabels = ['90S','60S','30S','Eq.','30N','60N','90N']

#Set cmap properties
bounds = np.array([0.001,0.01,0.1,1,5,10,25,50])
norm = colors.LogNorm(vmin=0.0001,vmax=50) #creates logarithmic scale
cmap = plt.get_cmap('jet')
cmap.set_over('#660000')  #everything above range of colormap

#Create basemap
fig,ax = plt.subplots(figsize=(15.,10.))
m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=0,urcrnrlon=360.,lon_0=180.,resolution='c')
m.drawcoastlines(linewidth=1)
m.drawcountries(linewidth=1)
m.drawparallels(np.arange(-90,90,30.),linewidth=0.3)
m.drawmeridians(np.arange(-180.,180.,45.),linewidth=0.3)   
meshlon,meshlat = np.meshgrid(lon,lat)
x,y = m(meshlon,meshlat)

#Plot variables
trend = m.pcolormesh(x,y,lintrends_120,cmap=cmap, norm=norm, shading='gouraud',vmin=0.0001,vmax=50)

#Set plot properties
#Colorbar
cbar=m.colorbar(trend, size='8%',ticks=bounds,extend="max",location='bottom',pad=0.8)
cbar.set_label(label='Linear Trend (mm/day/decade)',size=25)
cbar.set_ticklabels(bounds)
for t in cbar.ax.get_xticklabels():
     t.set_fontsize(20)
#Titles & labels
ax.set_title('c) 1979-2098',fontsize=35)
ax.set_xlabel('Longitude',fontsize=25)
ax.set_xticks(np.arange(0,405,45))
ax.set_xticklabels(lonlabels,fontsize=20)
ax.set_ylabel('Latitude',fontsize=25)
ax.set_yticks(np.arange(-90,120,30))
ax.set_yticklabels(latlabels,fontsize=20)

The colorbar block in the last chunk of code near the bottom.

The question

Is there a way to combine decimals (floats) AND integers in the colorbar tick labels so 1.0, 2.0, etc. will show up as 1, 2, etc. instead? I tried making two separate np.array() instances with decimals in one and integers in the other, but when I append them, they all turn into floats.

Upvotes: 1

Views: 4186

Answers (2)

Ianhi
Ianhi

Reputation: 3162

Try

bounds = ['0.001','0.01','0.1','1','5','10','25','50']
cbar.set_ticklabels(bounds)

Upvotes: 4

Gerrat
Gerrat

Reputation: 29710

It's hard to test, since your example isn't directly runnable, but you should just be able to set the labels to whatever string you like. Something like so:

bound_labels = [str(v) if v <=1 else str(int(v)) for v in bounds]
cbar.set_ticklabels(bound_labels)

Upvotes: 2

Related Questions