Align the size of the colorbar with matplotlib

What is this

When I make a graph with matplotlib, the color bar sticks out of the graph and it's awkward. I will show you how to align the color bars on the graph.

Various methods

1: Plot normally

colorbar1.py


import numpy
import matplotlib.pyplot

x = numpy.arange(10)
y = numpy.arange(10)
X, Y = numpy.meshgrid(x, y)
Z = X**2. + Y**2.

fig = matplotlib.pyplot.figure()
ax = fig.add_subplot(111)
im = ax.imshow(Z, interpolation='none')
fig.colorbar(im)

fig.savefig('colorbar1.png')

colorbar1.png

An example where the height of the main graph and the color bar happened to be the same.

2: Plot normally (sorry version)

colorbar2.py


import numpy
import matplotlib.pyplot

x = numpy.arange(15)
y = numpy.arange(10)
X, Y = numpy.meshgrid(x, y)
Z = X**2. + Y**2.

fig = matplotlib.pyplot.figure()
ax = fig.add_subplot(111)
im = ax.imshow(Z, interpolation='none')
fig.colorbar(im)

fig.savefig('colorbar2.png')

colorbar2.png

Once the aspect ratio of the main graph collapses, the color bars stick out up and down. sad. .. ..

3: Use mpl_toolkits.axes_grid1

colorbar3.py


import numpy
import matplotlib.pyplot
import mpl_toolkits.axes_grid1

x = numpy.arange(15)
y = numpy.arange(10)
X, Y = numpy.meshgrid(x, y)
Z = X**2. + Y**2.

fig = matplotlib.pyplot.figure()
ax = fig.add_subplot(111)
divider = mpl_toolkits.axes_grid1.make_axes_locatable(ax)
cax = divider.append_axes('right', '5%', pad='3%')
im = ax.imshow(Z, interpolation='none')
fig.colorbar(im, cax=cax)

fig.savefig('colorbar3.png')

colorbar5.png

The most common example on the net. How to use make_axes_locatable and append_axes in mpl_toolkits.axes_grid1. This is the solution. It was good.

4: But if you specify projection, ...

colorbar4.py


import numpy
import matplotlib.pyplot
import mpl_toolkits.axes_grid1

x = numpy.arange(15)
y = numpy.arange(10)
X, Y = numpy.meshgrid(x, y)
Z = X**2. + Y**2.

fig = matplotlib.pyplot.figure()
ax = fig.add_subplot(111, projection='polar')
divider = mpl_toolkits.axes_grid1.make_axes_locatable(ax)
cax = divider.append_axes('right', '5%', pad='3%')
im = ax.imshow(Z, interpolation='none')
fig.colorbar(im, cax=cax)

fig.savefig('colorbar4.png')

colorbar6.png

The color bar is not displayed! ?? Because type (cax) is matplotlib.projections.polar.PolarAxes. append_axes () does not have a projection argument and seems to use the projection of ax as it is. Is it possible to change the projection somehow? .. ..

5: Change cax position by yourself

colorbar4.py


import io
import numpy
import matplotlib.pyplot

x = numpy.arange(15)
y = numpy.arange(10)
X, Y = numpy.meshgrid(x, y)
Z = X**2. + Y**2.

fig = matplotlib.pyplot.figure()
ax = fig.add_subplot(111)
im = ax.imshow(Z, interpolation='none')
cax = fig.colorbar(im)

fig.savefig(io.BytesIO())

ax_pos = ax.get_position()
cax_pos0 = cax.ax.get_position()
cax_pos1 = [cax_pos0.x0, ax_pos.y0, cax_pos0.x1 - cax_pos0.x0, ax_pos.y1 - ax_pos.y0]
cax.ax.set_position(cax_pos1)

fig.savefig('colorbar5.png')

colorbar9.png

I was able to get the position of ax with get_position () and align it vertically using set_position () of cax. However, since ax.get_position () has a specification (?) That is not updated until fig.savefig () is executed, fig.savefig () will be called twice. This method is used in fig.savefig (bbox_inches ='tight').

Recommended Posts

Align the size of the colorbar with matplotlib
Increase the font size of the graph with matplotlib
About the size of matplotlib points
Match the colorbar to the figure with matplotlib
The basis of graph theory with matplotlib animation
Visualize the behavior of the sorting algorithm with matplotlib
Align the version of chromedriver_binary
Add information to the bottom of the figure with Matplotlib
Change the style of matplotlib
Adjust the ratio of multiple figures with the matplotlib gridspec
Reformat the timeline of the pandas time series plot with matplotlib
Let's visualize the number of people infected with coronavirus with matplotlib
I wrote the basic operation of matplotlib with Jupyter Lab
Increase the UI size of MyPaint
Unravel the mystery of matplotlib specgram
Later expand the disk size of Fedora CoreOS deployed with OVA
I tried to expand the size of the logical volume with LVM
[Python] Set the graph range with matplotlib
Adjust the spacing between figures with Matplotlib
[pyqtgraph] Set the size ratio of the graph
Check the existence of the file with python
Set the xticklabels color individually with matplotlib
The third night of the loop with for
Tips: Comparison of the size of three values
Display markers above the border with matplotlib
The second night of the loop with for
Check the file size with du -sh *
Count the number of characters with echo
Make common settings with subplot of matplotlib
[Python] How to specify the window display position and size of matplotlib
Adjust the bin width crisply and neatly with the histogram of matplotlib and seaborn
How to assign multiple values to the Matplotlib colorbar
The story of doing deep learning with TPU
Prepare the execution environment of Python3 with Docker
About the X-axis notation of Matplotlib bar graphs
[Python] limit axis of 3D graph with Matplotlib
2016 The University of Tokyo Mathematics Solved with Python
Change the font size of the legend in df.plot
Drawing tips with matplotlib on the server side
[Note] Export the html of the site with python.
See the behavior of drunkenness with reinforcement learning
Calculate the total number of combinations with python
Check the date of the flag duty with Python
One liner that lists the colors of matplotlib
Eliminate the inconveniences of QDock Widget with PySide
Challenge the Tower of Hanoi with recursion + stack
Rewrite the name of the namespaced tag with lxml
Fill the browser with the width of Jupyter Notebook
Animation with matplotlib
Predict the second round of summer 2016 with scikit-learn
Japanese with matplotlib
Dump the contents of redis db with lua
Tucker decomposition of the hay process with HOOI
Put the second axis in 2dhistgram of matplotlib
Find out the day of the week with datetime
Code for checking the operation of Python Matplotlib
Animation with matplotlib
Align Matplotlib graph colors with similar colors (color map)
Histogram with matplotlib
[Verification] Try to align the point cloud with the optimization function of pytorch Part 1
Convert the character code of the file with Python3