我正在使用 matplotlib 创建二维等高线图。使用提供的文档 http://matplotlib.org/examples/pylab_examples/contour_demo.html , 这样的等高线图可以通过
import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
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)
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)
plt.figure()
CS = plt.contour(X, Y, Z)
plt.clabel(CS, inline=1, fontsize=10)
plt.title('Simplest default with labels')
输出以下图。
文档详细说明了如何在现有图上手动标记某些等高线(或“线”)。我的问题是如何创建比显示的更多的轮廓线。
例如,显示的图有两个双变量高斯分布。右上角有 3 条等高线,分别为 0.5
、1.0
和 1.5
。
如何在 0.75
和 1.25
处添加轮廓线?
此外,我应该能够放大并(原则上)添加来自(例如)1.0
和 1.5
的数十条等高线。如何做到这一点?
最佳答案
要在指定的水平值绘制等值线,请在 .contour
中设置 levels
参数:
levels = np.arange(-1.0,1.5,0.25)
CS = plt.contour(X, Y, Z, levels=levels)
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
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)
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)
plt.figure()
levels = np.arange(-1.0,1.5,0.25)
CS = plt.contour(X, Y, Z, levels=levels)
plt.clabel(CS, inline=1, fontsize=10)
plt.title('levels = {}'.format(levels.tolist()))
plt.show()
The sixth figure here使用此方法在 levels = np.arange(-1.2, 1.6, 0.2)
处绘制等值线。
要放大,请设置所需区域的 x
限制和 y
限制:
plt.xlim(0, 3)
plt.ylim(0, 2)
要绘制 24 个自动选择的级别,请使用
CS = plt.contour(X, Y, Z, 24)
例如,
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
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)
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)
plt.figure()
N = 24
CS = plt.contour(X, Y, Z, N)
plt.clabel(CS, inline=1, fontsize=10)
plt.title('{} levels'.format(N))
plt.xlim(0, 3)
plt.ylim(0, 2)
plt.show()
The third figure here用这个方法画出6条等值线。
关于python - 使用 matplotlib 二维等高线绘图添加额外的等高线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31499689/