This question already has answers here:
Matplotlib 2 Subplots, 1 Colorbar
                                
                                    (9个答案)
                                
                        
                                2年前关闭。
            
                    
我正在尝试将通过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()


结果是下面的图像:



显然,包含在子图区域中的颜色栏使对齐不正确。

最佳答案

在写这个问题的过程中,我找到了解决方法,将颜色栏作为自己的轴,因此网格规格现在是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/

10-15 22:57