Reputation: 124
I'm plotting a 2D matrix, which has positive and negative values, in matplotlib using contourplot. It is supposed to show solid lines for positive values and dashed lines for negative values:
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()
However, this is what this code is plotting:
As you can see, there are dashed lines where it is supposed to show solid lines and solid lines where it is supposed to show dashed lines. Any ideas?
Edit: the code below works just fine:
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()
The output:
Upvotes: 2
Views: 1739
Reputation: 39042
You should switch the order of the line styles. Currently, your condition will assign -
(solid line) to contours where lvls >= 0
otherwise it will assign --
(dashed line). That's how the where
argument works.
In pseudo form, np.where(condition, A, B)
means if condition
is True
assign A
else assign B
Your present code (Not desired):
linestyles=np.where(lvls >= 0, "-", "--")
Right style (desired style):
linestyles=np.where(lvls >= 0, "--", "-")
Upvotes: 1