Reputation: 113
I am trying to plot a function using the contour()
function of matplotlib.pyplot
. I've tried to add clabel
to the plot but don't want labels to be added for every level, only the first few. From various demos and the documentation I got to the following:
import matplotlib.pyplot as plt
import numpy as np
def f(x1, x2):
return (x2 - x1)**4 + 8 * x2 * x1 - x1 + x2 + 3
x1 = np.linspace(-2,2,1000)
x2 = np.linspace(-2,2,1000)
X1, X2 = np.meshgrid(x1, x2)
F = f(X1, X2)
F = np.clip(F, a_min=None, a_max=50)
contours = plt.contour(X1, X2, F, 50, cmap="rainbow")
print(contours.levels)
plt.clabel(contours, contours.levels[0:8], inline=True, fontsize=10, fmt="f = %1.1f", use_clabeltext=True)
plt.title('Q3a Solution')
plt.xlabel('x1')
plt.ylabel('x2')
plt.show()
The code works when run in matplotlib version 2.1.2 however running the same code in version 3.0.0 gets the following error:
Traceback (most recent call last):
File "Tutorial1.py", line 16, in <module>
plt.clabel(contours, contours.levels[0:8], inline=True, fontsize=10, fmt="f = %1.1f", use_clabeltext=True)
File "/usr/local/lib/python3.7/site-packages/matplotlib/pyplot.py", line 2496, in clabel
return gca().clabel(CS=CS, *args, **kwargs)
TypeError: clabel() got multiple values for argument 'CS'
I've looked all over but can't work out if the usage of the clabel
has changed, or if this is a bug...
Upvotes: 1
Views: 1930
Reputation: 339570
It's a bug in matplotlib 3.0.0, which is now fixed. It'll be available with the upcoming 3.0.1 release.
Note that this is a pyplot
-only error. It does not occur when using the object oriented methods.
It is hence also not present in the contour label example. Please refer to that example in the meantime.
The easiest fix here is to use the axes
' methods instead of pyplot, i.e. plt.gca().clabel
instead of plt.clabel
import matplotlib.pyplot as plt
import numpy as np
def f(x1, x2):
return (x2 - x1)**4 + 8 * x2 * x1 - x1 + x2 + 3
x1 = np.linspace(-2,2,1000)
x2 = np.linspace(-2,2,1000)
X1, X2 = np.meshgrid(x1, x2)
F = f(X1, X2)
F = np.clip(F, a_min=None, a_max=50)
contours = plt.gca().contour(X1, X2, F, 50, cmap="rainbow")
print(contours.levels)
plt.gca().clabel(contours, contours.levels[0:8], inline=True, fontsize=10,
fmt="f = %1.1f", use_clabeltext=True)
plt.title('Q3a Solution')
plt.xlabel('x1')
plt.ylabel('x2')
plt.show()
Upvotes: 1