在Matplotlib轮廓2D和1D绘图中使用ColorBar legend对齐并共享X轴

2024-05-29 03:02:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图包括一个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.

很明显,包括在子图区域中的色条偏离了对齐。在


Tags: importgs绘图plotmatplotlibasnpfig
1条回答
网友
1楼 · 发布于 2024-05-29 03:02:36

在写这个问题的过程中,我找到了一个解决办法,把颜色条作为它自己的轴,这样网格规范现在是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.

不过,如果有更优雅的解决方案,我还是很感兴趣的。在

相关问题 更多 >

    热门问题