Strange range value in color bar, matplotlib

I am a new user for python and matplotlib, this may be a simple question, but I searched the Internet for many hours and could not find a solution for this.

I draw precipitation data that is in NetCDF format. What I find strange is that there are no negative values ​​in the data. (I checked it many times, just to make sure). But the value in the color bar starts with a negative value (for example, -0.0000312, etc.). This does not make sense, because I do not manipulate the data, others just select a part of the data from a large file and build it.

So my code is not really like it. Here is the code:

from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt from netCDF4 import Dataset cd progs f=Dataset('V21_GPCP.1979-2009.nc') lats=f.variables['lat'][:] lons=f.variables['lon'][:] prec=f.variables['PREC'][:] la=lats[31:52] lo=lons[18:83] pre=prec[0,31:52,18:83] m = Basemap(width=06.e6,height=05.e6,projection='gnom',lat_0=15.,lon_0=80.) x, y = m(*np.meshgrid(lo,la)) m.drawcoastlines() m.drawmapboundary(fill_color='lightblue') m.drawparallels(np.arange(-90.,120.,5.),labels=[1,0,0,0]) m.drawmeridians(np.arange(0.,420.,5.),labels=[0,0,0,1]) cs=m.contourf(x,y,pre,50,cmap=plt.cm.jet) plt.colorbar() 

The result I got for this code was a beautiful plot, with the color drum starting with a value of -0.00001893, and the rest were positive values, and I believe that they are correct. This is just the minimum value that pushes me.

I'd like to know:

  • Is there something wrong in my code? Because I know that the data is correct.
  • Is there a way to manually change the value to 0?
  • Is it correct to change the values ​​in the color bar every time we run the code, because for the same data, the next time I run the code, the values ​​will look like this: "-0.00001893, 2.00000000, 4.00000000, 6.00000000, etc. "
  • I want to configure them to "0.0, 2.0, 4.0, 6.0, etc."

Thank you, Vaishu

+4
source share
1 answer

Yes, you can manually format everything about the color bar. See this:

 import matplotlib.colors as mc import matplotlib.pyplot as plt plt.imshow(X, norm=mc.Normalize(vmin=0)) plt.colorbar(ticks=[0,2,4,6], format='%0.2f') 
  • Many build functions, including imshow , contourf and others, include the norm argument, which takes a Normalize object. You can set the vmin or vmax attributes of this object to configure the corresponding color bar values.

  • colorbar takes ticks and format arguments to configure which ticks to display and how to display them.

+2
source

All Articles