ZeroTwo
ZeroTwo

Reputation: 317

How to put contour labels as legend in a plot

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?

Upvotes: 1

Views: 1274

Answers (2)

jylls
jylls

Reputation: 4695

  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

Upvotes: 1

blunova
blunova

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

enter image description here

Upvotes: 1

Related Questions