I would like to generate a contour plot, using a 2 variable function, Z(X,Y). However, I would like to impose a condition that changes the function when X is less/greater than a certain value. Such a change would allow me to use just a singular plt.contour
line (i.e I do not want to create two separately defined functions, that results in using two separate plotting command lines).
I continue to run into (what I believe to be) truth/logic errors. My guess is that some aspect of the numpy meshgrid does not comply with that conditional "switch" of the function. Attached below is the short code to display the concept, along with the full Traceback error. If anything is unclear, or if what I have provided is insufficient to explain my problem, please feel free to comment below.
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(0,50,100)
Y = np.linspace(0,50,100)
X, Y = np.meshgrid(X,Y)
def z(x,y):
if x < 20:
return np.sin(x) + np.cos(y)
else:
return np.tan(x * y)
Z = z(X,Y)
plt.contourf(X, Y, Z)
plt.xlabel('x')
plt.ylabel('y')
plt.colorbar()
ValueError Traceback (most recent call last)
<ipython-input-29-7e200be093e6> in <module>
16
17
---> 18 Z = z(X,Y)
19
20 plt.figure(figsize=(8,6))
<ipython-input-29-7e200be093e6> in z(x, y)
9
10 def z(x,y):
---> 11 if x < 20:
12 return np.sin(x) + np.cos(y)
13
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()```