【问题标题】:Contourplot in matplot showing incorrect linestylematplot中的等高线图显示不正确的线型
【发布时间】:2021-10-05 03:53:18
【问题描述】:

我正在使用轮廓图在 matplotlib 中绘制具有正值和负值的 2D 矩阵。它应该显示正值的实线和负值的虚线:

loc = matplotlib.ticker.MaxNLocator(20)
Z = psi
lvls = loc.tick_values(Z.min(), Z.max())
fig, ax = plt.subplots(figsize=(7,7))
cp = plt.contour(X, Y, Z, 20, colors='k', linestyles=where(lvls >= 0, "-", "--"))
plt.xlabel('X')
plt.ylabel('Y')
plt.clabel(cp, inline=True, fontsize=10)
plt.gca().set_aspect('equal', adjustable='box')
plt.title('Stream function - Re = ' + str(Re) + ', t = {:.2f}'.format((t)*dt))
plt.savefig('SF' + '_Re' + str(Re) + '_N' + str(nx) + '_o' + str(order) + '_SF' + '.png')
plt.close()

但是,这就是这段代码正在绘制的内容:

如您所见,在应该显示实线的地方有虚线,在应该显示虚线的地方有实线。有什么想法吗?

编辑:下面的代码可以正常工作:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker

nx = 100
ny = 100

# Generate 2D mesh
x = 2*np.pi*np.arange(0,nx,1)/(nx)
#x = linspace(0,Lx,nx,endpoint=True)
y = 2*np.pi*np.arange(0,ny,1)/(ny)
#y = linspace(0,Ly,ny,endpoint=True)
X, Y = np.meshgrid(x, y,indexing='ij')

Z = -np.sin(X/2)*np.cos(Y**1.5)

loc = matplotlib.ticker.MaxNLocator(20)
lvls = loc.tick_values(Z.min(), Z.max())
fig, ax = plt.subplots(figsize=(7,7))
cp = plt.contour(X,Y,Z,20, colors='k', linestyles=np.where(lvls >= 0, "-", "--"))
plt.clabel(cp, inline=True, fontsize=10)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()

输出:

【问题讨论】:

    标签: python matplotlib contour


    【解决方案1】:

    您应该切换线条样式的顺序。目前,您的条件会将-(实线)分配给lvls >= 0 的轮廓,否则它将分配--(虚线)。这就是where 参数的工作原理。

    在伪形式中,np.where(condition, A, B) 表示如果conditionTrue 分配A 否则分配B


    您当前的代码(不需要):

    linestyles=np.where(lvls >= 0, "-", "--")
    

    正确的样式(想要的样式):

    linestyles=np.where(lvls >= 0, "--", "-")
    

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      相关资源
      最近更新 更多