python - Matplotlib 挑战 - 改变等高线图中的线条样式

标签 python matplotlib contour

我想使用 numpy 的 bool 索引来仅绘制满足特定条件的函数区域 - sigma < 0,如下面的代码所示。当我尝试像本例一样使用 numpy 的 bool 索引时 - change_line_style ,我得到类型错误。有没有办法使用 numpy 的 bool 索引来使用等高线函数仅绘制某些区域?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)

plt.figure()
plt.ylim([-2,2])
plt.xlim([-0.5,0.5])

plt.xlabel(r'\lambda')
plt.ylabel(r'u')

lambda_x = np.linspace(-0.5,0.5,1000)
u = np.linspace(-2,2,1000)

X,Y = np.meshgrid(lambda_x,u)
# Drawing f=0 lines for implicit function f(u;lambda) = lambda*u  + u**3 - u**5
f1 = X  + Y**2 - Y**4
f2 = Y

sigma = X + 3*Y**2 - 5*Y**4

stable = sigma < 0
#plt.setp(zc, linewidth=4)
print stable.shape
print f1.shape

plt.contour(X[stable],Y[stable], f1[stable], levels = [0],colors = ('r'),linewidths = 4,extend='both')
plt.contour(X[stable],Y[stable], f2[stable], levels = [0],colors = ('b'),linewidths = 4,extend='both')

plt.show()

最佳答案

知道了!

我使用了 numpy.ma.masked_where() 函数,如这段代码所示:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)

plt.figure()
plt.ylim([-2,2])
plt.xlim([-0.5,0.5])

lambda_x = np.linspace(-0.5,0.5,1000)
u = np.linspace(-2,2,1000)

X,Y = np.meshgrid(lambda_x,u)
# Drawing f=0 lines for implicit function f(u;lambda) = lambda*u  + u**3 - u**5
f1 = X  + Y**2 - Y**4
f2 = Y

sigma = X + 3*Y**2 - 5*Y**4

unstable = sigma > 0
stable = sigma < 0

#for i in range(0,10):
    #f1[i] = f1[i][stable[i]]

plt.contour(np.ma.masked_where(unstable, X),np.ma.masked_where(unstable, Y), np.ma.masked_where(unstable, f1), levels = [0],colors = ('r'),linewidths = 4,extend='both')
plt.contour(np.ma.masked_where(stable, X),np.ma.masked_where(stable, Y), np.ma.masked_where(stable, f1), levels = [0],colors = ('b'),linewidths = 4,linestyles = 'dashed',extend='both')
plt.contour(np.ma.masked_where(unstable, X),np.ma.masked_where(unstable, Y), np.ma.masked_where(unstable, f2), levels = [0],colors = ('r'),linewidths = 4,extend='both')
plt.contour(np.ma.masked_where(stable, X),np.ma.masked_where(stable, Y), np.ma.masked_where(stable, f2), levels = [0],colors = ('b'),linewidths = 4,linestyles = 'dashed',extend='both')

plt.show()

关于python - Matplotlib 挑战 - 改变等高线图中的线条样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27213784/

相关文章:

python - 如何提取特定类别之前的最后 3 个索引号

python pandas plot 系列 matplotlib

c++ - 如何使用Opencv轮廓单向描述线点

python - 使用 Python 的 matplotlib 3D API 绘制轮廓的问题

openCV 完全检测形状轮廓的问题

python - CouchDB 是否有与 Redis 的 expire 等效的功能?

python - 维度为 1 的 numpy 数组与没有该维度的 numpy 数组有什么区别

python - 无法使用 pip 在 Linux 盒子上安装 torch

python - python 中的图形图上有很多边

python - 强制所有 x 轴值在 Python 的散点图中进行比较