I'm plotting a 2D temperature array over a world map, using Basemap. All works fine, except for the colorbar, that I want to fix within a certain range Tmin-Tmax. Unfortunately, vmin and vmax that I use for matplotlib, here seem not to work and I wasn't able to find the right keywords (if any) used for this purpose. Any suggestion? Thanks.
fig = plt.figure(figsize=(20,10))
map = Basemap(projection='cyl', lat_0 = 57, lon_0 = -135, resolution = RES, area_thresh = 0.1, llcrnrlon=-180., llcrnrlat=-90., urcrnrlon=180., urcrnrlat=90.)
map.drawcoastlines()
map.drawcountries()
map.drawparallels(np.arange(-90,90,15),labels=[1,1,0,1])
map.drawmeridians(np.arange(-180,180,15),labels=[1,1,0,1])
map.drawmapboundary()
map.imshow(IR1)
cbar = map.colorbar(location='right', pad="5%")
cbar.set_label('T [Celsius]')
plt.title("temperature")
plt.savefig("temperature.png")
Here I give an idea by using np.ma.masked. Any advice on my work would be appreciate.
I use an netcdf file and read the temperature of the whole area. This is similar with your job.
Before setting vmin and vmax
### Read the file
wrf_file1 = "wrf_201401.nc"
t_m1 = gdal.Open('NETCDF:"'+wrf_file1+'":T2')
lon = gdal.Open('NETCDF:"'+wrf_file1+'":XLONG')
lat = gdal.Open('NETCDF:"'+wrf_file1+'":XLAT')
### plot
fig =plt.figure(figsize=(6,4))
ax = plt.subplot()
map = basemap(llcrnrlon=xxx,llcrnrlat=xxx,urcrnrlon=xxx,urcrnrlat=xxx)
x, y = map(lon.ReadAsArray()[362], lat.ReadAsArray()[362])
t = t_m1.ReadAsArray()[30,:,:] ### select one dataframe
cf = map.pcolormesh(x, y,t,cmap=plt.cm.Spectral_r,alpha = 0.8)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="3%", pad=0.4)
cbar = plt.colorbar(cf, cax=cax)
plt.show()
The colorbar represent that the temperature were range from 268.5 to 281.
If I want to plot the area which temperature were range from 270 to 275. Here is my solution.
Improvement
fig =plt.figure(figsize=(6,4))
ax = plt.subplot()
t = t_m1.ReadAsArray()[30,:,:]
t_mask_1 = np.ma.masked_greater(t,275)
t_mask_2 = np.ma.masked_less(t_mask_1,270)
cf = map.pcolormesh(x, y,t_mask_2,cmap=plt.cm.Spectral_r,alpha = 0.8)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="3%", pad=0.4)
cbar = plt.colorbar(cf, cax=cax)
plt.show()
Related
I am plotting various parameters in three different subplots. My second and third subplots are overlapping and I'm not understanding what is causing it. I have specified ax1, ax2, and ax3 and I'm thinking the issue may be from fig.add_subplot() but I'm not sure how to fix it. See my code below for reference. I only included the portions for the set up of the figure and the final plot since all three plots are generated practically in the same manner. I also included an image of what the plot is looking like that I wish to fix.
# Convert dataframe to 2D maps
lon_grid, lat_grid = np.meshgrid(data.lon.unique(), data.lat.unique())
L_grid = data.L.values.reshape(len(data.lat.unique()), len(data.lon.unique()))
Lam_grid = data.lam.values.reshape(len(data.lat.unique()), len(data.lon.unique()))
R_grid = data.R2.values.reshape(len(data.lat.unique()), len(data.lon.unique()))
# Make figures
fig = plt.figure(figsize= (10, 30), facecolor='white')
ax1 = fig.add_subplot(1,1,1,projection=ccrs.PlateCarree())
ax2 = fig.add_subplot(2,1,2,projection=ccrs.PlateCarree())
ax3 = fig.add_subplot(3,1,3,projection=ccrs.PlateCarree())
# Draw coastlines, states and countries for plot 3
ax3.coastlines()
ax3.add_feature(cfeature.BORDERS)
ax3.add_feature(cfeature.STATES)
# Draw parallels and meridians for plot 3
parallels = np.arange(-90,91,30)
meridians = np.arange(-180,181,60)
gl = ax3.gridlines(crs=ccrs.PlateCarree(), draw_labels=False,
linewidth=2, color='gray', alpha=0.5, linestyle='--')
gl.xlocator = mticker.FixedLocator(meridians)
gl.ylocator = mticker.FixedLocator(parallels)
ax3.set_xticks(np.arange(-180,181,30), crs=ccrs.PlateCarree())
ax3.set_yticks(parallels, crs=ccrs.PlateCarree())
lon_formatter = LongitudeFormatter(zero_direction_label=True)
lat_formatter = LatitudeFormatter()
ax3.xaxis.set_major_formatter(lon_formatter)
ax3.yaxis.set_major_formatter(lat_formatter)
# Add Longitude wrap-around points at 0/360 for plot 3
cyclic_R_grid, cyclic_lons = cutil.add_cyclic_point(R_grid, coord=data.lon.unique())
c3 = ax3.contourf(cyclic_lons, data.lat.unique(), cyclic_R_grid, alpha = 1.0,
transform=ccrs.PlateCarree(), levels = np.arange(0,100), \
vmin = 0.0, vmax = 100.0)
# Overplot rigidity
c3_ = ax3.imshow(np.flip(R_grid, axis=1), interpolation = 'gaussian', alpha = 0.6, extent = (-180,180,-90,90))
cbar = plt.colorbar(c3, ax=ax3, fraction=0.025)
cbar.set_label('R')
plt.show()
You are adding your subplots wrong. fig.add_subplot expects n_rows,n_cols, index in that order. So the correct definition would be
fig = plt.figure(figsize= (10, 30), facecolor='white')
ax1 = fig.add_subplot(3,1,1,projection=ccrs.PlateCarree())
ax2 = fig.add_subplot(3,1,2,projection=ccrs.PlateCarree())
ax3 = fig.add_subplot(3,1,3,projection=ccrs.PlateCarree())
def plot_rain(num, show=False):
i = 0
for x in range(num):
ifile = "{:02d}".format(x)
saveimg_name = 'noaa_images/rain/rain.f0{}.png'.format(ifile)
data, _, lats, lons, datetime = collect_data(ifile, RAIN)
lons = np.apply_along_axis(lambda row: row - 360, 1, lons)
# 0.0001, 0.003,0.0005 make no blue background not sure why
cint = np.arange(0.0001, 0.003,0.0005)
fig, ax = plt.subplots()
# Create new figure
mapcrs = ccrs.Mercator(central_longitude=263, min_latitude=23, max_latitude=50, globe=None)
# Set data projection
datacrs = ccrs.PlateCarree()
gs = gridspec.GridSpec(2, 1, height_ratios=[1, .02], bottom=.07,
top=.99, hspace=0.01, wspace=0.01)
# Add the map and set the extent
ax = plt.subplot(gs[0], projection=mapcrs, frameon=False)
ax.set_extent([293, 233 , 23, 55], ccrs.PlateCarree())
ax.set_frame_on(False)
# Add state/country boundaries to plot
ax.add_feature(cfeature.STATES)
ax.add_feature(cfeature.BORDERS)
#Choose colormap https://matplotlib.org/2.0.1/users/colormaps.html
cf = ax.contourf(lons, lats, data, cint, cmap=plt.cm.jet,transform=datacrs, alpha=0.7)
# add color bar and title
# fig.text(.2, .12, "Kg of rainfall per m^2 s",fontweight="bold")
# cb = fig.colorbar(cf, pad=0, aspect=50, orientation='horizontal')
ax.axis('off')
i = i + 1
if show:
plt.show()
else:
plt.savefig(saveimg_name, transparent=True, bbox_inches='tight', pad_inches=0,quality =100,progressive= True)
This above code will generate an image and then I use folium to overlay the image on a map.
Image1 is what it looks like without adding title and color bar.
Here is what it looks like with title and color bar
I use this code
fig.text(.2, .12, "Kg of rainfall per m^2 s",fontweight="bold")
cb = fig.colorbar(cf, pad=0, aspect=50, orientation='horizontal')
After I added title and color bar, the original plots are shrunk. What I want is to add color bar and title without affecting the size of the plot. Thanks for the help!
To avoid resizing of existing axes when adding a colorbar you can give the colorbar its own axes via the cax keyword argument. Here is a minimal example as I cannot reproduce your plot without more data.
fig, ax = plt.subplots()
c = ax.imshow(np.random.random((10, 10)))
cbar_ax = fig.add_axes([0.1, 0.1, 0.05, 0.8])
# new ax with dimensions of the colorbar
cbar = fig.colorbar(c, cax=cbar_ax)
plt.show()
I am having issues with a plot that I have created where I am getting an unwanted additional color palette on the plot.
My script uses to list of data to create a plot with colored points.
plt.close('all')
fig, axes = plt.subplots(nrows = 1, ncols = 1)
fig.set_facecolor('white')
axes.set_ylabel('$dz$ [$\AA$]')
axes.set_xlabel('Time [ns]')
axes.spines['right'].set_visible(False)
axes.spines['top'].set_visible(False)
axes.yaxis.set_ticks_position('left')
axes.xaxis.set_ticks_position('bottom')
axes.tick_params(direction='out')
#axes.set_title('N/A')
axes.set_ylim(-20,10)
axes.set_xlim(0, 90)
cmap = plt.get_cmap('plasma')
colors = [cmap(i) for i in np.linspace(0, 1, 9)]
# Make Color Bar ------------------------------------------------------
cax = 0
divider = make_axes_locatable(axes)
cax = divider.append_axes('right', size='5%', pad=0.1)
im = axes.imshow(np.linspace(1, 8.5, 100).reshape(10, 10), cmap='plasma')
fig.colorbar(im, cax=cax)
#----------------------------------------------------------------------
for i, dist in enumerate(dz):
if i % 100 == 0:
x = i / 1000
y = dist
phval = final_pH_array[i]
axes.plot(x, y, 'k.', markersize = 4 , color = colors[int(phval)], clip_on = False)
plt.savefig('plot.pdf')
plt.show()
The results looks like this:
As you can see there is an additional color bar / color palette that I don't want on the plot but can't seem to get rid of it.
Any help with this would be great!
I think im.set_visible(False) should achieve what you want.
But maybe you should take a look at plt.scatter. scatter returns a PathCollection that you can pass to the colorbar function.
Background
For plotting 2-d spatial distribution of some attribute, contourf and pcolormesh are both good choice as a visualization form.
Due to the actual meaning of the plotting data, I want to set the value nearby zero are showing in white color(for example, [-0.2,0.2]); and zero value should be the midpoint
From the question [Defining the midpoint of a colormap in matplotlib, I tried to set vmin and vmax to adjust the colormap.
Data import
import pygrib
grib='fnl_20141110_12_00.grib2';
grbs=pygrib.open(grib)
grb = grbs.select(name='Vertical velocity')[8]#Vertical velocity
data=grb.values
lat,lon = grb.latlons()
1. Contourf plot
m = Basemap(llcrnrlon=110,llcrnrlat=34,urcrnrlon=122,urcrnrlat=44,projection='mill')
fig=plt.figure(figsize=(8,4))
ax1 = plt.subplot(121)
x, y = m(lon, lat)
cs = m.contourf(x,y,data,cmap=plt.cm.RdBu)
cb = m.colorbar(cs,"bottom", size="5%", pad="8%")
ax1.set_title("Original",fontsize = 15)
ax2 = plt.subplot(122)
cs = m.contourf(x,y,data,cmap=plt.cm.RdBu,vmin = -1.8,vmax =1.8)
cb = m.colorbar(cs,"bottom", size="5%", pad="8%")
ax2.set_title("symmetrical vmin & vmax",fontsize = 15)
2. Pcolormesh plot
m = Basemap(llcrnrlon=110,llcrnrlat=34,urcrnrlon=122,urcrnrlat=44,projection='mill')
fig=plt.figure(figsize=(8,4))
ax1 = plt.subplot(121)
cs = m.pcolormesh(x,y,data,cmap=plt.cm.RdBu)
cb = m.colorbar(cs,"bottom", size="5%", pad="8%")
ax1.set_title("Original",fontsize = 15)
ax2 = plt.subplot(122)
cs = m.pcolormesh(x,y,data,cmap=plt.cm.RdBu,vmin = -1.8,vmax =1.8)
cb = m.colorbar(cs,"bottom", size="5%", pad="8%")
ax2.set_title("symmetrical vmin & vmax",fontsize = 15)
I upload the data here as an .grib2 file. If you are interested, you can download it
My doubt
With the contourf plot type, setting symmetrical vmin and vmax couldn't adjust zeron to the midpoint of the colormap. That's different from pcolormesh.
The same colormap RdBu_r ==> different result in contourf and pcolormesh. In pcolormesh plot, the middle partof colorbar are shown in white color. But in contourf plot, the white color seemed to be ignored.
I have 8 plots that I want to compare with 8 different but corresponding plots. So I set up 8 subplots, then try to use axes_grid1.make_axes_locatable to divide the subplots. However, it appears that when I use the new_vertical function it returns something of the type matplotlib.axes.AxesSubplot.
Here's the code I have:
fig = plt.figure()
for i in range(7):
ax = fig.add_subplot(4,2,i+1)
idarray = ice_dict[i]
mdarray = model_dict[i]
side_by_side(ax, idarray, mdarray)
def side_by_side(ax1, idata, mdata):
from mpl_toolkits.axes_grid1 import make_axes_locatable
global mycmap
global ice_dict, titles
divider = make_axes_locatable(ax1)
ax2 = divider.new_vertical(size="100%", pad=0.05)
fig1 = ax1.get_figure()
fig1.add_axes(ax2)
cax1 = divider.append_axes("right", size = "5%", pad= 0.05)
plt.sca(ax1)
im1 = ax1.pcolor(idata, cmap = mycmap)
ax1.set_xlim(space.min(), space.max()+1)
ax1.set_ylim(0, len(idata))
plt.colorbar(im1, cax=cax1)
im2 = ax2.pcolor(mdata, cmap = mycmap)
ax2.set_xlim(space.min(), space.max()+1)
for tl in ax2.get_xticklabels():
tl.set_visible(False)
ax2.set_ylim(0, len(mdata))
ax2.invert_yaxis()
Which produces something like this, where ax2 is on top and ax1 is on bottom in each subplot:
I should probably mention that they're on a different scale so I cant just use the same colorbar for both. Thanks in advance.
tl;dr how can I get a colorbar on ax2, an AxesSubplot, as well as ax1, an Axes? Or is there a better way to get the same look?