惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

有赞技术团队
有赞技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
IT之家
IT之家
博客园 - 【当耐特】
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
MyScale Blog
MyScale Blog
WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Hugging Face - Blog
Hugging Face - Blog
I
InfoQ
B
Blog RSS Feed
腾讯CDC
云风的 BLOG
云风的 BLOG
N
Netflix TechBlog - Medium
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
雷峰网
雷峰网
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
D
DataBreaches.Net
The Cloudflare Blog
V
V2EX
S
SegmentFault 最新的问题

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
How to Plot Only One Colorbar for Multiple Plot Using Mat...
2017-06-11 · via jdhao's digital space

In some situations, we have several subplots and we want to use only one colorbar for all the subplots. How to do this in Matplotlib?

Two ways can be employed.

The conventional method#

The first method is like normal plotting: first draw the main plot, then add a colorbar to the main plot. Matplotlib provide different ways to add a colorbar: explicit or implicit way.

The explicit way#

The idea is to adjust the existing axes manually to make room for an additional colorbar. Then explicitly add an axes where the colorbar resides. See the code below for details:

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(8.5, 5))

for ax in axes.flat:
    ax.set_axis_off()
    im = ax.imshow(np.random.random((16, 16)), cmap='viridis',
                   vmin=0, vmax=1)

fig.subplots_adjust(bottom=0.1, top=0.9, left=0.1, right=0.8,
                    wspace=0.02, hspace=0.02)

# add an axes, lower left corner in [0.83, 0.1] measured in figure coordinate with axes width 0.02 and height 0.8

cb_ax = fig.add_axes([0.83, 0.1, 0.02, 0.8])
cbar = fig.colorbar(im, cax=cb_ax)

 set the colorbar ticks and tick labels
cbar.set_ticks(np.arange(0, 1.1, 0.5))
cbar.set_ticklabels(['low', 'medium', 'high'])

plt.show()

In this way, we can control the position of colorbar precisely. The output image is like this:

The implicit way#

Matplotlib also offers method which can adjust the existing axes and make room for a colorbar implicitly. See the code below for an example:

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(8.5, 5))

for ax in axes.flat:
    ax.set_axis_off()
    im = ax.imshow(np.random.random((16, 16)), cmap='viridis',
                   vmin=0, vmax=1)

# notice that here we use ax param of figure.colorbar method instead of

# the cax param as the above example

cbar = fig.colorbar(im, ax=axes.ravel().tolist(), shrink=0.95)

cbar.set_ticks(np.arange(0, 1.1, 0.5))
cbar.set_ticklabels(['low', 'medium', 'high'])

plt.show()

In this way, you have to manually tweak the shrink param of fig.colorbar method to make the main plot and the colorbar appear the same height. See the output image below

Both the two methods have an disadvantage that it is difficult to control the padding space between subplots. You have to adjust the figure aspect ratio and also the padding params to make the padding between the subplots appear the same. In fact, the padding in horizontal and vertical direction is not the same for the above two plots even after tweaking.

Using the axesgrid approach#

Matplotlib also provides a AxesGrid toolkit to deal with padding and colorbar issues arising from plotting multiple subplots. By using axesgrid, the padding between subplots are guaranted to be the same. Also the colorbar have exactly the same height as the main plot. Following is a working example showing how to use axesgrid:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid
import numpy as np

fig = plt.figure(figsize=(6, 4))

grid = AxesGrid(fig, 111,
                nrows_ncols=(2, 3),
                axes_pad=0.05,
                cbar_mode='single',
                cbar_location='right',
                cbar_pad=0.1
                )

for ax in grid:
    ax.set_axis_off()
    im = ax.imshow(np.random.random((16,16)), vmin=0, vmax=1)

# when cbar_mode is 'single', for ax in grid, ax.cax = grid.cbar_axes[0]

cbar = ax.cax.colorbar(im)
cbar = grid.cbar_axes[0].colorbar(im)

cbar.ax.set_yticks(np.arange(0, 1.1, 0.5))
cbar.ax.set_yticklabels(['low', 'medium', 'high'])
plt.show()

See the output image below.

You can see that the padding between subplots are all the same, also the colorbar have the same height as the main plot. Conveniently, isn’t it?

Summary#

Using the normal way is more flexible but also annoying because you have to adjust the paramters by trial and error. By employing the axesgrid, you can simplify the plotting of multiple plot with just one colorbar, significantly. In my opinion, the latter way is prefered.

References#