[Python] Adjusting the color bar

Vocabulary Book. Reprinting a lot because it is troublesome to search every time. There is an original URL.

[matplotlib.pyplot.colorbar] (https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.colorbar.html) [Qiita @ skotaro: A story dedicated to those who have found out by dissecting the colorbar of matplotlib, or who do not want to have trouble adjusting the colorbar anymore] (https://qiita.com/skotaro/items/01d66a8c9902a766a2c0)

Adjust position: Draw a color bar on the specified Axes

Specified by fig.add_axes

Specified with the cax = option.

fig = plt.figure(figsize=(8,5))
ax  = fig.add_axes((0.05, 0.15, 0.9, 0.8))
im  = ax.imshow(np.random.random((10, 20)), cmap='jet')
cax = fig.add_axes((0.05, 0.05, 0.9, 0.08))
plt.colorbar(im, orientation='horizontal', cax=cax)

image.png

Specified by make_axes_locatable

The method of drawing the color bar is the same as above, only the method of making Axes is changed.

from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)

#Make space to the right
cax = divider.new_horizontal(size="2%", pad=0.05)
fig.add_axes(cax)
# OR
cax = divider.append_axes('right', '5%', pad='3%')

plt.colorbar(im, cax=cax)

Qiita @ termoshtt: Align colorbar to figure with matplotlib

However, if you specify projection for ax, it does not work.

Qiita @ nishimuraatsushi: Align the size of colorbar with matplotlib

Draw color bar alone

plt.figure(figsize=(8, 0.5))
norm = mcolors.DivergingNorm(vcenter=0.0, vmin=-5, vmax=5)
im   = ax.imshow(np.array([[0,1]]), cmap='bwr', norm=norm)
plt.gca().set_visible(False)
cax = plt.axes([0.1, 0.2, 0.8, 0.6])
cb  = plt.colorbar(im, orientation='horizontal', cax=cax)

[stackoverflow: Standalone colorbar (matplotlib)] (https://stackoverflow.com/questions/16595138/standalone-colorbar-matplotlib)

The above code is drawn once with ʻimshow → then define ʻAxes for the color bar, and so on.

--Save this color bar alone → Edit with pptx etc. --Create a function that passes an axes to draw a color bar and an image (ʻim` in the above code) as arguments.

In that case, this is enough. The latter example:

def draw_coloarbar(ax, im):
    return plt.colorbar(im, orientation='horizontal', cax=ax)

fig  = plt.figure(figsize=(8, 4))
ax   = fig.add_axes((0.05, 0.05, 0.9, 0.9))
im   = ax.imshow(np.array(np.random.random((10, 20))), cmap='jet')
cax = fig.add_axes([0.1, 0.45, 0.8, 0.1])
draw_coloarbar(cax, im)

image.png

However, in the function that does not pass the image as an argument = it is necessary to do a temporary ʻimshow`

When creating a function that draws only the colorbar on the specified ʻAxes (after doing a tentative ʻimshow), the method of specifying the position is different:

def draw_coloarbar2(ax):
    norm = mcolors.DivergingNorm(vcenter=0.0, vmin=-5, vmax=5)
    im = ax.imshow(np.array([[0,1]]), cmap='bwr', norm=norm)
    ax.set_visible(False)
    return plt.colorbar(im, orientation='horizontal', #cax=ax) # cax=If so, the color bar will not be displayed
                        ax=ax, fraction=1.0)

fig  = plt.figure(figsize=(8, 4))
ax   = fig.add_axes((0.05, 0.05, 0.9, 0.9))
im   = ax.imshow(np.array(np.random.random((10, 20))), cmap='jet')
cax = fig.add_axes([0.1, 0.45, 0.8, 0.1])
draw_coloarbar2(cax)

image.png

In this case, it is necessary to specify the position with ʻax = instead of cax = . See the link at the top of the page for the differences in the meanings of these arguments. fraction =` is an argument of how much of the specified Axes should be used for the color bar.

Shape adjustment

When changing the thickness, ʻaspect =`

plt.colorbar(aspect=20) #thin
plt.colorbar(aspect=50) #thick

[stackoverflow: How to decrease colorbar WIDTH in matplotlib?] (https://stackoverflow.com/questions/33443334/how-to-decrease-colorbar-width-in-matplotlib)

To add triangles to both ends of the color bar ʻextend =`

plt.colorbar(extend='both') #Triangle on both ends

Adjusting the scale

Use cbar.set_ticks () for the position of the scale and cbar.set_ticklabels () for the character string of the scale.

[Akira Takeshima's Web Page: Color Bar] (http://hydro.iis.u-tokyo.ac.jp/~akira/page/python/contents/plot/general/colorbar.html) [matplotlib: pylab_examples example code: colorbar_tick_labelling_demo.py] (https://matplotlib.org/examples/pylab_examples/colorbar_tick_labelling_demo.html)

Get the scale

Note that the calling method differs between ticks and ticklabels.

ticks = cbar.get_ticks()
ticklabels = [ticklabel.get_text() for ticklabel in cbar.ax.get_xticklabels()]

Even when changing only ticklabels, I get angry with set_ticks () must have been called. The same thing is specified as cbar.set_ticks (ticks).

For example, if you want to add a unit to the colorbar:

#the above-5 to 5 color bars as cbar
ticks = cbar.get_ticks() # [-4. -2.  0.  2.  4.]
ticklabels = [ticklabel.get_text() for ticklabel in cbar.ax.get_xticklabels()]
# ['−4', '−2', '0', '2', '4']
ticklabels[-1] += ' [unit]'
cbar.set_ticks(ticks)
cbar.set_ticklabels(ticklabels)

image.png

Change font size

cbar.ax.tick_params(labelsize=10)

[stackoverflow: Change fontsize of colorbars in matplotlib] (https://stackoverflow.com/questions/40184696/change-fontsize-of-colorbars-in-matplotlib)

Recommended Posts

[Python] Adjusting the color bar
[Python] Adjusted the color map standard
[Python] A progress bar on the terminal
[Python] Get the main color from the screenshot
Create a color bar with Python + Qt (PySide)
The one that displays the progress bar in Python
the zen of Python
[Python] Split the date
[ev3dev × Python] Color sensor
Fill the background with a single color with OpenCV2 + Python
[Python] Summary of how to specify the color of the figure
python3 Measure the processing speed.
Towards the retirement of Python2
Download the file in Python
Find the difference in Python
Compare the Python array-like guys
About the Python module venv
About the ease of Python
[Python] Get the previous month
Blender 2.9, Python, hexadecimal color specification
[Python 2/3] Parse the format string
bar chart race in python
Call the API with python3.
About the features of Python
[Python] Check the installed libraries
I downloaded the python source
The Power of Pandas: Python
Find the maximum python (improved)
Color extraction with Python + OpenCV solved the mystery of the green background
Leave the troublesome processing to Python
[Python] Check the current directory, move the directory
Extract the xz file with python
The story of Python and the story of NaN
Getting the arXiv API in Python
Check the behavior when assigning Python
[Python] Find the second smallest value.
First Python 3 ~ The beginning of repetition ~
Color the integration interval with matplotlib.pyplot
Python in the browser: Brython's recommendation
Save the binary file in Python
AtCoder: Python: Daddy the sample test.
Hit the Sesami API in Python
Try the Python LINE Pay SDK
[python] Clock that changes color (animation)
[Python] Hit the Google Translation API
Get the desktop path in Python
Progress bar in pop-up in Python Kivy
[Python] What is @? (About the decorator)
Existence from the viewpoint of Python
Get the weather with Python requests
Get the weather with Python requests 2
pyenv-change the python version of virtualenv
Get the script path in Python
In the python command python points to python3.8
Implement the Singleton pattern in Python
How to get the Python version
Find the Levenshtein Distance with python
[python] What is the sorted key?
Change the Python version of Homebrew
Hit the Etherpad-lite API with Python
Install the Python plugin with Netbeans 8.0.2