1

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()

The output is: enter image description here

I want the labels for each contour as a legend in the corner, not along the contour lines. Is there a way?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
ZeroTwo
  • 307
  • 1
  • 3
  • 12
  • The legend is created with the following content when referenced from the [reference](https://matplotlib.org/stable/api/contour_api.html). `handles, lables = CS1.legend_elements('y');plt.legend(handles, lables, loc='upper right')` – r-beginners Jun 29 '22 at 14:25

2 Answers2

1
  1. This post here shows a couple of ways to create a legend for your contours. Specifically, you can use
for i in range(len(cl)): 
  CS1.collections[i].set_label(cl[i].get_text())

to create a custom legend for your contours.

  1. To remove the labels from the contours inside the plot, you can use the solution posted here. It consists in iteratively removing the labels with 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:

enter image description here

jylls
  • 4,395
  • 2
  • 10
  • 21
1

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()

enter image description here

blunova
  • 2,122
  • 3
  • 9
  • 21