使用颜色条图例

时间:2018-02-24 19:49:06

标签: python matplotlib plot legend contour

我试图在2D轮廓图中包含一维路径,作为等高线图下方的单独图。理想情况下,这些将具有共享和对齐的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.

显然,子图区域中包含的颜色条会丢弃对齐。

1 个答案:

答案 0 :(得分:1)

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

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