python - 使用 matplotlib 二维等高线绘图添加额外的等高线

标签 python matplotlib plot

我正在使用 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')

输出以下图。 enter image description here

文档详细说明了如何在现有图上手动标记某些等高线(或“线”)。我的问题是如何创建比显示的更多的轮廓线。

例如,显示的图有两个双变量高斯分布。右上角有 3 条等高线,分别为 0.51.01.5

如何在 0.751.25 处添加轮廓线?

此外,我应该能够放大并(原则上)添加来自(例如)1.01.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()

enter image description here

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()

enter image description here

The third figure here用这个方法画出6条等值线。

关于python - 使用 matplotlib 二维等高线绘图添加额外的等高线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31499689/

相关文章:

r - 如何在 R 或 MATLAB 中为散点图创建带阴影的误差条 "box"

c# - 绘制一个点

python - Unity3d - 在 Google App Engine 上托管

python - 我应该如何绘制 XYZ 数据点以在 python 中创建 RGB 深度图像

python - 指定层的顺序

python-3.x - 创建 32 位图像并另存为 tif

python - 使用 Python 从 mySQL 数据库绘制图表

python - 强制特定函数签名

python - pandas - 检查数据框 groupby 中的非唯一值

r - R 中倒置条形图中的线条