python-3.x - 3个子图中的2个以上的水平颜色条

标签 python-3.x matplotlib axes colorbar

有人知道如何优雅地在三个子图中的两个上绘制水平色标,并在第三个子图上绘制一个附加的水平色标。

理想情况下,颜色条应具有与相应图像轴相同的x尺寸。除了使用matplotlib.gridspec设置整个图像网格外,我没有找到任何好的解决方案。

绘制单个颜色条可以与mpl_toolkits.axes_grid1.ImageGrid完美配合,但是在尝试在三个轴中的两个轴上绘制颜色条时会失败。

最佳答案

这个想法是使用fig.add_axes在颜色条所在的位置添加轴。
这是一个例子:

import numpy as np
import matplotlib.pyplot as plt

matrix = np.random.random((10, 10, 3))

fig, ax = plt.subplots(1,3, figsize=(12, 3))
plt.subplots_adjust(left=0.05, right=0.85)
for i in range(3):
    im = ax[i].imshow(matrix[:, :, i], interpolation='nearest')
    ax[i].set_aspect("equal")

plt.draw()
p0 = ax[0].get_position().get_points().flatten()
p1 = ax[1].get_position().get_points().flatten()
p2 = ax[2].get_position().get_points().flatten()
ax_cbar = fig.add_axes([p0[0], 0, p1[2]-p0[0], 0.05])
plt.colorbar(im, cax=ax_cbar, orientation='horizontal')

ax_cbar1 = fig.add_axes([p2[0], 0, p2[2]-p2[0], 0.05])
plt.colorbar(im, cax=ax_cbar1, orientation='horizontal')

plt.show()

example_colorbar

编辑:fig.add_axes的文档说:

Add an axes at position rect [left, bottom, width, height] where all quantities are in fractions of figure width and height.



因此,要将颜色条放在图表的顶部,您只需要将bottom参数更改为1。


ax_cbar = fig.add_axes([p0[0], 0, p1[2]-p0[0], 0.05])
ax_cbar1 = fig.add_axes([p2[0], 0, p2[2]-p2[0], 0.05])


ax_cbar = fig.add_axes([p0[0], 1, p1[2]-p0[0], 0.05])
ax_cbar1 = fig.add_axes([p2[0], 1, p2[2]-p2[0], 0.05])

enter image description here

关于python-3.x - 3个子图中的2个以上的水平颜色条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41428442/

相关文章:

r - 用变化的刻度进行缩放(轴限制)

通过 multiprocessing.pool 的 Python3 并行代码比顺序代码慢

python - 黑色背景上的 IPython qtconsole 内联绘图无法正常工作

python - 如何使用 matplotlib 打印摄氏符号?

python - 如何在 matplotlib 中设置轴限制?

r - ggplot2:x 轴刻度之间的条形图

python - 使用时间模块测试复杂性

python - 从 Entry 获取信息

python - 在基于 trio 的 Python 应用程序中生成进程并在进程之间进行通信

python - Python 中的seaborn : barplot appears upside down