Create a grayscale colorbar for each subplot in python
Question:
I have two polygon patch plots with shading in grayscale, with each patch added to an axis. and I would like to add a colorbar underneath each subplot.
I’m using
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
poly=mpatches.Polygon(verts,color=rgb,ec='black') #create patch
ax.add_patch(poly) #add patch to axis
plt.set_cmap('gray') #grayscale colormap
#verts,rgb input created in above lines of code
The colorbars should be in grayscale and have range [0,1], with 0 being black, 0.5 marked, and 1 being white. im using subplot(121) and (122).
Thanks in advance.
Answers:
To use colorbars you have to have some sort of ScalarMappable
instance (this is used for imshow
, scatter
, etc.):
mappable = plt.cm.ScalarMappable(cmap='gray')
# the mappable usually contains an array of data, here we can
# use that to set the limits
mappable.set_array([0,1])
ax.colorbar(mappable)
I might be late here but now matplotlib has unique functionality to set colormap to gray as shown in this link.
plt.gray()
fig = plt.figure(figsize=(10, 10))
plt.subplots_adjust(left = 0, right = 1, top = 1, bottom = 0)
im = plt.imshow(output)
pos = fig.add_axes([0.93, 0.1, 0.02, 0.35]) # Set colorbar position in fig
fig.colorbar(im, cax=pos) # Create the colorbar
plt.savefig(os.path.join(args.output_path, image_name))
the line 1 will set your colormap to grayscale. the result is shown in the image.
I have two polygon patch plots with shading in grayscale, with each patch added to an axis. and I would like to add a colorbar underneath each subplot.
I’m using
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
poly=mpatches.Polygon(verts,color=rgb,ec='black') #create patch
ax.add_patch(poly) #add patch to axis
plt.set_cmap('gray') #grayscale colormap
#verts,rgb input created in above lines of code
The colorbars should be in grayscale and have range [0,1], with 0 being black, 0.5 marked, and 1 being white. im using subplot(121) and (122).
Thanks in advance.
To use colorbars you have to have some sort of ScalarMappable
instance (this is used for imshow
, scatter
, etc.):
mappable = plt.cm.ScalarMappable(cmap='gray')
# the mappable usually contains an array of data, here we can
# use that to set the limits
mappable.set_array([0,1])
ax.colorbar(mappable)
I might be late here but now matplotlib has unique functionality to set colormap to gray as shown in this link.
plt.gray()
fig = plt.figure(figsize=(10, 10))
plt.subplots_adjust(left = 0, right = 1, top = 1, bottom = 0)
im = plt.imshow(output)
pos = fig.add_axes([0.93, 0.1, 0.02, 0.35]) # Set colorbar position in fig
fig.colorbar(im, cax=pos) # Create the colorbar
plt.savefig(os.path.join(args.output_path, image_name))
the line 1 will set your colormap to grayscale. the result is shown in the image.