Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Legend | Section
Data Visualization & EDA
Avsnitt 1. Kapitel 10
single

single

bookLegend

Svep för att visa menyn

When a chart contains multiple elements, adding a legend helps clarify what each element represents. matplotlib offers several ways to create a legend.

First Option

You can define all labels directly inside plt.legend():

123456789101112131415161718
import numpy as np import matplotlib.pyplot as plt questions = ['question_1', 'question_2', 'question_3'] yes_answers = np.array([500, 240, 726]) no_answers = np.array([432, 618, 101]) answers = np.array([yes_answers, no_answers]) positions = np.arange(len(questions)) width = 0.3 for i in range(len(answers)): plt.bar(positions + width * i, answers[i], width) plt.xticks(positions + width*(len(answers)-1)/2, questions) plt.legend(['positive answers', 'negative answers']) plt.show()
copy

This creates a legend in the upper-left corner by passing a list of labels into plt.legend().

Second Option

You can also assign labels directly inside plotting functions using the label= parameter:

1234567891011121314151617181920
import matplotlib.pyplot as plt import numpy as np questions = ['question_1', 'question_2', 'question_3'] positions = np.arange(len(questions)) yes_answers = np.array([500, 240, 726]) no_answers = np.array([432, 618, 101]) answers = [yes_answers, no_answers] labels = ['positive answers', 'negative answers'] width = 0.3 for i in range(len(answers)): plt.bar(positions + width*i, answers[i], width, label=labels[i]) plt.xticks(positions + width*(len(answers)-1)/2, questions) plt.legend() plt.show()
copy

Here, plt.legend() automatically gathers labels from the plotted elements.

Third Option

You can also set labels using the set_label() method of the returned artist:

12345678910111213141516171819202122
import matplotlib.pyplot as plt import numpy as np questions = ['question_1', 'question_2', 'question_3'] positions = np.arange(len(questions)) yes_answers = np.array([500, 240, 726]) no_answers = np.array([432, 618, 101]) answers = [yes_answers, no_answers] width = 0.3 labels = ['positive answers', 'negative answers'] for i in range(len(answers)): bar = plt.bar(positions + width*i, answers[i], width) bar.set_label(labels[i]) center_positions = positions + width*(len(answers)-1)/2 plt.xticks(center_positions, questions) plt.legend(loc='upper center') plt.show()
copy

Legend Location

The loc argument controls where the legend appears. The default 'best' asks matplotlib to choose an optimal location automatically.

12345678910111213141516171819202122
import matplotlib.pyplot as plt import numpy as np questions = ['question_1', 'question_2', 'question_3'] positions = np.arange(len(questions)) yes_answers = np.array([500, 240, 726]) no_answers = np.array([432, 618, 101]) answers = [yes_answers, no_answers] labels = ['positive answers', 'negative answers'] width = 0.3 for i, label in enumerate(labels): bars = plt.bar(positions + width*i, answers[i], width) bars.set_label(label) center_positions = positions + width*(len(answers)-1)/2 plt.xticks(center_positions, questions) plt.legend(loc='upper center') plt.show()
copy

Valid values for loc include: 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'center'.

Note
Study More

You can explore more in legend() documentation

Uppgift

Swipe to start coding

  1. Label the lowest bars as 'primary sector' specifying the appropriate keyword argument.
  2. Label the bars in the middle as 'secondary sector' specifying the appropriate keyword argument.
  3. Label the top bars as 'tertiary sector' specifying the appropriate keyword argument.
  4. Place the legend on the right side, centered vertically.

Lösning

Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 10
single

single

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt