Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot pcolor colorbar in a different subplot - matplotlib

I am trying to split my plots in different subplots.. What I want to achieve is to put a colorbar for a subplot in a different subplot. Right now I am using:

# first graph
axes = plt.subplot2grid((4, 2), (0, 0), rowspan=3)
pc = plt.pcolor(df1, cmap='jet')

# second graph
axes = plt.subplot2grid((4, 2), (3, 0))
plt.pcolor(df2, cmap='Greys')

# colorbar
plt.subplot2grid((4, 2), (0, 1), rowspan=3)
plt.colorbar(pc) 

But the result is the following (notice the unwanted empty graph left to the colorbar): Wrong graph

What can I do to print only the colorbar without the left plot?

Thanks

like image 377
gc5 Avatar asked Sep 18 '13 13:09

gc5


People also ask

How do you add a Colorbar to a subplot?

Create a figure and a set of subplots wuth two rows and two columns. Make a list of colormaps. Iterate the axes and create a pseudocolor plot with a non-regular rectangular grid. Make colorbars with the same axes of pcolormesh.

How do I change the Colorbar scale in Matplotlib?

To set a Colorbar range, call matplotlib. pyplot. clim(vmin, vmax) with vmin as the lower bound for color scaling and vmax as the upper bound for color scaling.

How do I split a subplot in Matplotlib?

We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots. They are the fractions of axis width and height, respectively.

What is the Matplotlib Pyplot function that plots a Colorbar on the side of a plot?

The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale.


1 Answers

colorbar() accepts a cax keyword argument that allows you to specify the axes object that the colorbar will be drawn on.

In your case, you would change your colorbar call to the following:

# colorbar
axes = plt.subplot2grid((4, 2), (0, 1), rowspan=3)
plt.colorbar(pc, cax=axes)

This will take up the whole space given by subplot2grid; you can adjust this to be more reasonable either by having the main axes take up many more columns than the colorbar axes, or by setting up the gridspec explicitly. For example, your figure may be easier to tweak with the following:

from matplotlib import gridspec
gs = gridspec.GridSpec(2, 2, height_ratios=(3, 1), width_ratios=(9, 1))

# first graph
axes = plt.subplot(gs[0,0])
pc = plt.pcolor(df1, cmap='jet')

# second graph
axes = plt.subplot(gs[1,0])
plt.pcolor(df2, cmap='Greys')

# colorbar
axes = plt.subplot(gs[0,1])
plt.colorbar(pc, cax=axes)

Then you can just change height_ratios and width_ratios to your liking.

like image 178
tbekolay Avatar answered Sep 24 '22 13:09

tbekolay