Description of the problem
For an image like this, I'd like to set the colorbar on the right to the same height as the main image
methodologies
0. Description of parameters
/stable/api/_as_gen/?highlight=colorbar#
1. (im, fraction=0.046, pad=0.04, shrink=1.0)
The fraction can be adjusted from 0.035-0.046 to find the right size.
However, it may not work when the length and height contrast of the image is too large
2. make_axes_locatable
This is a function from the matplotlib package
from mpl_toolkits.axes_grid1 import make_axes_locatable im = (data) divider = make_axes_locatable(()) cax = divider.append_axes("right", size="5%", pad="3%") (im, cax=cax)
Doesn't work for axes with projection parameters (will report an error), e.g. cartopy's GeoAxes
3. make_axes_locatables upgrades
/questions/18195758/set-matplotlib-colorbar-size-to-match-graph @Matthias
import as plt from mpl_toolkits import axes_grid1 def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs): """Add a vertical color bar to an image plot.""" divider = axes_grid1.make_axes_locatable() width = axes_grid1.axes_size.AxesY(, aspect=1./aspect) pad = axes_grid1.axes_size.Fraction(pad_fraction, width) current_ax = () cax = divider.append_axes("right", size=width, pad=pad) (current_ax) return (im, cax=cax, **kwargs)
usage example
im = ((200).reshape((20, 10))) add_colorbar(im)
4. manually add an axe to the colorbar
/questions/18195758/set-matplotlib-colorbar-size-to-match-graph @Fei Yao
import as plt import numpy as np fig=() ax = () im = ((100).reshape((10,10))) # Create an axes for colorbar. The position of the axes is calculated based on the position of ax. # You can change 0.01 to adjust the distance between the main image and the colorbar. # You can change 0.02 to adjust the width of the colorbar. # This practice is universal for both subplots and GeoAxes. cax = fig.add_axes([ax.get_position().x1+0.01,ax.get_position().y0,0.02,ax.get_position().height]) (im, cax=cax) # Similar to (im, cax = cax)
Effective demonstration
summarize
To this article on how to use Python to modify the location of the main picture to align the article is introduced to this, more related Python to modify the location of the content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!