python - Matplotlib:颜色条的高度与绘图的高度相同

标签 python matplotlib plot colorbar

<分区>

我正在绘制一些二维数据,如图所示。轴方面应该相等,轴范围应该不同。

import numpy
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

#Generate data
delta = 0.025

x = numpy.arange(-5.0, 5.0, delta)
y = numpy.arange(-5.0, 5.0, delta)

X, Y = numpy.meshgrid(x, y)

Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

#Plot
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1,  aspect='equal')

PC = ax1.pcolor(X, Y, Z)
CF = ax1.contour(X, Y, Z, 50, colors = "black")

plt.xlim(-4.0, 4.0)
plt.ylim(-2.0, 2.0)

cbar = plt.colorbar(PC)
cbar.add_lines(CF)

plt.show()

enter image description here

如何使颜色条与绘制数据的高度相同?

最佳答案

您可以使用 make_axes_locatable 执行此操作:

import numpy
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from mpl_toolkits.axes_grid1 import make_axes_locatable

#Generate data
delta = 0.025

x = numpy.arange(-5.0, 5.0, delta)
y = numpy.arange(-5.0, 5.0, delta)

X, Y = numpy.meshgrid(x, y)

Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

#Plot
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1,  aspect='equal')

PC = ax1.pcolor(X, Y, Z)
CF = ax1.contour(X, Y, Z, 50, colors = "black")

plt.xlim(-4.0, 4.0)
plt.ylim(-2.0, 2.0)

divider = make_axes_locatable(ax1)
cax1 = divider.append_axes("right", size="5%", pad=0.05)

cbar = plt.colorbar(PC, cax = cax1)
cbar.add_lines(CF)

plt.show()

enter image description here

关于python - Matplotlib:颜色条的高度与绘图的高度相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26034777/

相关文章:

Python cx_Oracle。用 executemany() 敲头

python - 使用 Python 从单尾分布生成范围内的随机数

python - 3D 绘图区域满足 matplotlib 中的不等式

r - plotly 中 plot_geo 函数的悬停文本

python - 为什么 signal.SIGTERM 在我的主线程中没有得到正确处理?

python - 在 BigQuery 中运行 python 函数

python - 如何使 x 和 y 轴标签的文本大小以及 matplotlib 和 prettyplotlib 图形上的标题更大

python - 具有各种 y 轴的子图中的纵横比

python - 如何自动设置x轴的大小

r - 如何在 R Studio 中绘制具有 13 个节点的二叉树