使用matplotlib二维等高线绘制添加额外等高线

2024-06-02 07:05:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

例如,所示的曲线图有两个二元高斯曲线。右上角有三条等高线,分别位于0.51.01.5

我怎样才能在0.751.25添加等高线?

此外,我应该能够放大并(原则上)从(例如)1.01.5添加几十条等高线。怎么做到的?


Tags: 文档importmatplotlibasnpcmpltexamples
1条回答
网友
1楼 · 发布于 2024-06-02 07:05:56

要在指定的级别值上绘制等值线,请设置the ^{} parameter

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条等值线。

相关问题 更多 >