python - 多个子图大小一致的 Matplotlib 颜色条
问题描述
我正在尝试创建一个包含几个具有公共颜色条的子图的图形。子图必须具有相等的纵横比,并且颜色条必须具有与子图相同的高度。但是,我无法获得与其他子图高度相同的窄色条。
我正在使用这个配方生成一个颜色条,其范围适用于所有子图;因此这个问题在 MWE 中没有解决。
使用轴分隔器配方附加颜色条时,子图的高度会因纵横比而变化。
这是MWE
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import itertools as it
import numpy as np
mean = [0, 0]
cov = [[1, 0.5],
[0.5, 4]]
n_samples = 10000
hrange = [[-5,5],[-5,5]]
bins = 20
# RANDOM DATA
Z_random = np.random.multivariate_normal(mean, cov, size=n_samples)
Z, xedges, yedges = np.histogram2d(Z_random[:,0], Z_random[:,1], bins=bins, range=hrange, normed=True)
X, Y = np.meshgrid(xedges, yedges)
# PLOT PCOLORMESHS
fig, axes = plt.subplots(2,3, subplot_kw=dict(aspect="equal"))
axes = dict(enumerate(fig.get_axes(),1))
for i,ax in axes.items():
if i==6:
break
pcm = ax.pcolormesh(X,Y,Z)
# PLOT COLORBAR
divider = make_axes_locatable(axes[6])
cax = divider.append_axes("left", size="15%", pad=0.0)
fig.colorbar(pcm, cax=cax, label=r"Colorbar label")
我可以在完整的子图上绘制颜色条,在这种情况下高度是正确的,但它的宽度要吸引人。
有没有人有一个“强大”的解决方案,即没有手动摆弄持有颜色条的子图的尺寸?
提前致谢!
编辑:增加颜色条的宽度以强调它的高度变小。
解决方案
如果唯一的目的是让颜色条的高度与其水平邻居正确对齐,那么这个答案的最后一个解决方案会有所帮助。
但是,如果您还希望颜色条与其顶部的图左对齐,则解决方案可能更复杂。
您可以使用回调来明确设置颜色条的位置,如下所示:
from matplotlib import pyplot as plt
from matplotlib.transforms import Bbox
import numpy as np
mean = [0, 0]
cov = [[1, 0.5],
[0.5, 4]]
n_samples = 10000
hrange = [[-5,5],[-5,5]]
bins = 20
# RANDOM DATA
Z_random = np.random.multivariate_normal(mean, cov, size=n_samples)
Z, xedges, yedges = np.histogram2d(Z_random[:,0], Z_random[:,1], bins=bins, range=hrange, normed=True)
X, Y = np.meshgrid(xedges, yedges)
# PLOT PCOLORMESHS
fig, axes = plt.subplots(2,3, subplot_kw=dict(aspect="equal"))
for i,ax in enumerate(axes.flat):
if i==5:
break
pcm = ax.pcolormesh(X,Y,Z)
# PLOT COLORBAR
cax = fig.add_axes([0.6,0.01,0.1,0.4])
fig.colorbar(pcm, cax=cax, label=r"Colorbar label")
def align_cbar(cax, hax, vax):
hpos = hax.get_position()
vpos = vax.get_position()
bb = Bbox.from_extents(vpos.x0, hpos.y0, vpos.x0+vpos.width*.05,hpos.y1)
if cax.get_position() != bb:
cax.set_position(bb)
fig.canvas.draw_idle()
align_cbar(cax, axes[1,1], axes[0,2])
fig.canvas.mpl_connect("draw_event", lambda x: align_cbar(cax, axes[1,1], axes[0,2]))
plt.show()
推荐阅读
- visual-studio-code - VSCode:Markdown 文件使用 3 个空格而不是制表符缩进列表项
- openlayers - Openlayers 6.9.0,无法创建生产包
- javascript - Google Sheet + Script + 将文件夹 ID 从一个脚本返回到另一个脚本
- react-router - 如何通过反应路由器设置状态而不重新渲染所有组件?
- python - 使用 csv 数据标记 matplotlib 中的数据点
- asp.net - 浏览器未将 Cookie 传递给 IFrame
- github - 与创建本地到远程存储库相关的 GitHub 问题
- python - Python 在等式两边应用/迭代操作
- javascript - 每次运行调用它的函数时,webkitSpeechRecognition 总是请求麦克风访问权限
- android-studio - 我正在使用带有 Action Web Search 的 Android Intent 类 - 我希望 Web 搜索响应来自 google 搜索的图像而不是 ALL