Showing Levels end values on contourf
Question:
I’m using a contourf to plot my data (var) and I would like to have 20 levels going from -100 to 100, so this what I did.
plt.contourf(var, levels=np.linspace(-100, 100, 21))
But when I plot it it will miss the end values (-100 and 100), how can I solve it and show these values?
Thanks in advance.
Answers:
You can have a fine control of the values shown in the colorbar:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.mgrid[-2:2:100j,-2:2:100j]
z = 100 * np.cos(x**2 + y**2)
fig, ax = plt.subplots()
c = ax.contourf(x, y, z, levels=np.linspace(-100, 100, 21))
cb = fig.colorbar(c)
ticks = np.linspace(-100, 100, 9)
# if you change ticks, you want to change the following as well
labels = [str(int(t)) for t in ticks]
cb.set_ticks(ticks, labels=labels)
I’m using a contourf to plot my data (var) and I would like to have 20 levels going from -100 to 100, so this what I did.
plt.contourf(var, levels=np.linspace(-100, 100, 21))
But when I plot it it will miss the end values (-100 and 100), how can I solve it and show these values?
Thanks in advance.
You can have a fine control of the values shown in the colorbar:
import numpy as np
import matplotlib.pyplot as plt
x, y = np.mgrid[-2:2:100j,-2:2:100j]
z = 100 * np.cos(x**2 + y**2)
fig, ax = plt.subplots()
c = ax.contourf(x, y, z, levels=np.linspace(-100, 100, 21))
cb = fig.colorbar(c)
ticks = np.linspace(-100, 100, 9)
# if you change ticks, you want to change the following as well
labels = [str(int(t)) for t in ticks]
cb.set_ticks(ticks, labels=labels)