Reputation: 317
I am plotting contours, using an example from this link (code and output plot below) https://www.geeksforgeeks.org/matplotlib-pyplot-contour-in-python/
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib
delta = 0.15
x = np.arange(1.5, 2.5, delta)
y = np.arange(1.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z = (np.exp(X - Y))
CS1 = plt.contour(X, Y, Z)
fmt = {}
strs = ['1', '2', '3', '4', '5', '6', '7']
for l, s in zip(CS1.levels, strs):
fmt[l] = s
plt.clabel(CS1, CS1.levels, inline = True,
fmt = fmt, fontsize = 10)
plt.title('matplotlib.pyplot.contour() Example')
plt.show()
I want the labels for each contour as a legend in the corner, not along the contour lines. Is there a way?
Upvotes: 1
Views: 1274
Reputation: 4695
for i in range(len(cl)):
CS1.collections[i].set_label(cl[i].get_text())
to create a custom legend for your contours.
label.remove()
Below is what the final code looks like:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib
delta = 0.15
x = np.arange(1.5, 2.5, delta)
y = np.arange(1.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z = (np.exp(X - Y))
CS1 = plt.contour(X, Y, Z)
fmt = {}
strs = ['1', '2', '3', '4', '5', '6', '7']
for l, s in zip(CS1.levels, strs):
fmt[l] = s
cl=plt.clabel(CS1, CS1.levels,fmt=fmt, inline = False, fontsize = 10)
plt.title('matplotlib.pyplot.contour() Example')
for i in range(len(cl)):
CS1.collections[i].set_label(cl[i].get_text())
for label in cl:
label.remove()
plt.legend()
And the output gives:
Upvotes: 1
Reputation: 2532
Try this:
delta = 0.15
x = np.arange(1.5, 2.5, delta)
y = np.arange(1.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z = (np.exp(X - Y))
CS1 = plt.contour(X, Y, Z)
nm, lbl = CS1.legend_elements()
lbl_ = [i for i in range(1, len(lbl))]
plt.legend(nm, lbl_)
plt.title('matplotlib.pyplot.contour() Example')
plt.show()
Upvotes: 1