python - 将 Matplotlib 轮廓 2D 和 1D 图中的 X 轴与颜色条图例对齐并共享

标签 python matplotlib plot legend contour

我试图将通过 2D 等值线图的 1D 路径作为等值线图下方的单独图包含在内。理想情况下,它们将具有共享且对齐的 X 轴,以引导读者了解绘图的特征,并包含颜色条图例。

我做了这个最小的例子来展示我的尝试和问题。

import numpy as np
import matplotlib.pyplot as plt 
from matplotlib import gridspec

# Generating dummy data

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z = np.outer(np.cos(y), np.cos(3*x))


# Configure the plot
gs = gridspec.GridSpec(2,1,height_ratios=[4,1])
fig = plt.figure()

cax = fig.add_subplot(gs[0])

# Contour plot
CS = cax.contourf(X, Y, Z)

# Add line illustrating 1D path
cax.plot([-3,3],[0,0],ls="--",c='k')

cbar = fig.colorbar(CS)

# Simple linear plot
lax = fig.add_subplot(gs[1],sharex=cax)

lax.plot(x, np.cos(3*x))
lax.set_xlim([-3,3])

plt.show()

结果如下:

Illustrating the problem with the colour bar.

显然,子图区域中包含的颜色条偏离了对齐。

最佳答案

在编写这个问题的过程中,我找到了一种解决方法,将颜色条作为它自己的轴,这样网格规范现在是一个 2x2 子图网格。

import numpy as np
import matplotlib.pyplot as plt 
from matplotlib import gridspec


delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z = np.outer(np.cos(y), np.cos(3*x))

# Gridspec is now 2x2 with sharp width ratios
gs = gridspec.GridSpec(2,2,height_ratios=[4,1],width_ratios=[20,1])
fig = plt.figure()

cax = fig.add_subplot(gs[0])

CS = cax.contourf(X, Y, Z)
cax.plot([-3,3],[0,0],ls="--",c='k')

lax = fig.add_subplot(gs[2],sharex=cax)

lax.plot(x, np.cos(3*x))
lax.set_xlim([-3,3])

# Make a subplot for the colour bar
bax = fig.add_subplot(gs[1])

# Use general colour bar with specific axis given.
cbar = plt.colorbar(CS,bax)

plt.show()

This gives the desired result.

如果有任何更优雅的解决方案,我仍然会感兴趣。

关于python - 将 Matplotlib 轮廓 2D 和 1D 图中的 X 轴与颜色条图例对齐并共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48966920/

相关文章:

Python matplotlib - 如何为垂直线添加注释

r - 绘制最佳拟合线 R

r - 创建 stackoverflow.com 的用户图像模式,identicon

matlab - Matlab 中的双刻度标签

python - 安装后如何让 Anaconda3 看到 Python 2.7?

python - 了解 OpenCV 示例 stereo_match.py​​ 代码

python - 有一个列表,我需要从中查找重复项

python - Matplotlib 只保存没有空格的文本

python - 在 matplotlib 中为补丁轮廓添加模糊?

python - 将 bool 数据帧转换为二进制数数组