Plot a chart with a title and legend from a DataFrame
Expt. No.19
Page No.38
Chart with title and legend
Aim
To write a Python program that plots the subject-wise averages of two sections, stored in a DataFrame, as a line chart with a title and a legend.
Concepts used
Algorithm
- Create a DataFrame with Subject, XII-A and XII-B columns.
- Plot XII-A and XII-B against Subject with plt.plot(), giving each a label.
- Add axis labels, a title and the legend.
- Show the chart.
Program
# Comparing two sections with a line chart and a legend import pandas as pdimport matplotlib.pyplot as plt df = pd.DataFrame({"Subject": ["English", "Maths", "Physics", "Chemistry", "IP"], "XII-A": [72, 65, 70, 68, 84], "XII-B": [69, 74, 66, 71, 80]})print(df) plt.plot(df["Subject"], df["XII-A"], marker="o", label="XII-A")plt.plot(df["Subject"], df["XII-B"], marker="s", label="XII-B")plt.xlabel("Subject")plt.ylabel("Average marks")plt.title("Section-wise average marks")plt.legend()plt.show()
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python plot_dataframe_legend.py
Subject XII-A XII-B
0 English 72 69
1 Maths 65 74
2 Physics 70 66
3 Chemistry 68 71
4 IP 84 80
✓ Printed by running this program, not typed by hand.
Result
The chart has one line per section, and the legend tells them apart. XII-B did better in Maths and Chemistry; XII-A did better in English, Physics and IP.
Viva voce: what the examiner may ask
01What does label= do in plt.plot()?
It gives the line a name, which the legend displays.
02What does plt.legend() do?
It draws the box that names each line or set of bars.
03What does marker="o" do?
It draws a circle at each data point.
Variations for the lab test
- Draw the same data as a bar chart for one section.
- Change the line styles with
linestyle="--". - Move the legend with
plt.legend(loc="lower right").
! Common mistake Calling
plt.legend() when no plot has a label= shows an empty legend and a warning.