Unwanted Color Palette on Plot - python

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.

Related

Positioning Multiple Colorbars outside of Subplots (matplotlib)

I have a figure with multiple subplot rows that all share an x axis.
Some of the rows require a color bar, but the other rows don't.
If I just use the color bar function, the subplots will be misaligned.
How do I place the color bars outside of the subplots such that all the rows will still be aligned?
I made a function that may help:
import numpy as np
from matplotlib import pyplot as plt
#function to add colorbar for imshow data and axis
def add_colorbar_outside(im,ax):
fig = ax.get_figure()
bbox = ax.get_position() #bbox contains the [x0 (left), y0 (bottom), x1 (right), y1 (top)] of the axis.
width = 0.01
eps = 0.01 #margin between plot and colorbar
# [left most position, bottom position, width, height] of color bar.
cax = fig.add_axes([bbox.x1 + eps, bbox.y0, width, bbox.height])
cbar = fig.colorbar(im, cax=cax)
#Example code:
x = np.random.random((10, 100))
fig, axes = plt.subplots(5,1, sharex = True)
im = axes[0].imshow(x, cmap = "Reds", aspect="auto", origin="lower")
add_colorbar_outside(im, axes[0])
im2 = axes[2].imshow(x, cmap = "coolwarm", aspect="auto", origin="lower")
add_colorbar_outside(im2, axes[2])
plt.show()

How to Prevent Overlapping of Subplots in Python?

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())

cmap.set_under() and cmap.set_over() not appearing in colorbar

I am trying to plot a color bar and I tried using cmap.set_under() and cmap.set_over(), however they do not appear on the plot, can anyone help me please?
Here is the code:
city = 'Portugal, Lisbon'
G = ox.graph_from_place(city, network_type='drive', simplify=True)
G_nx = nx.relabel.convert_node_labels_to_integers(G)
nc =[whatever you would like]
ns=[whatever you would like]
cmap = copy(plt.cm.get_cmap('inferno_r'))
cmap.set_over((0.001462, 0.000466, 0.013866, 1.0))
cmap.set_under((0.988362, 0.998364, 0.644924, 1.0))
norm=plt.Normalize(vmin=0.8, vmax=1.5)
sm = mpl.cm.ScalarMappable(norm=norm, cmap=cmap)
sm.set_array([])
fg_color = 'black'
fig, ax = ox.plot.plot_graph(G_nx, node_color=nc, node_size=ns, edge_linewidth=0.8, figsize = (80,40), show=False, bgcolor = 'white')
cb = fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax, orientation='vertical', aspect=50, shrink=0.8)
cb.set_label('r', fontsize = 60, color = fg_color, rotation = 'horizontal')
cb.ax.tick_params(labelsize=40, color = fg_color)
# set colorbar tick color
cb.ax.yaxis.set_tick_params(color=fg_color)
cb.outline.set_edgecolor(fg_color)
cb.cmap.set_over('k')
plt.setp(plt.getp(cb.ax.axes, 'yticklabels'), color=fg_color)
fig.set_frameon(True)
fig.savefig('dhgdhg.png', facecolor=fig.get_facecolor(), bbox_inches='tight')
Thank you in advance
fig.colorbar(..., extend='both') adds little triangular arrows at the top and the bottom of the colorbar, to indicate the over and the under color. Instead of 'both', other options are 'min' and 'max', the default is 'neither'. For more info, see the docs.
Note that the default under color is equal to the lowest color of the colormap (similar for the default over color). In case these are the desired values, they don't need to be set explicitly.

Prevent color bar and title from affecting size of the plot in Matplotlib

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()

fix colorbar range in basemap python

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()

Categories

Resources