ByteBoard Notes Notes

Plot a chart with a title and legend from a DataFrame

Informatics Practices XII · Experiment 19 of 38 · Pandas

★ CBSE suggested12-IPMatplotlib programs
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

  1. Create a DataFrame with Subject, XII-A and XII-B columns.
  2. Plot XII-A and XII-B against Subject with plt.plot(), giving each a label.
  3. Add axis labels, a title and the legend.
  4. 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
Figure 1
Line chart of section-wise average marks: XII-A 72, 65, 70, 68, 84 and XII-B 69, 74, 66, 71, 80 across English, Maths, Physics, Chemistry and IP, with a legend.

✓ 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

  1. Draw the same data as a bar chart for one section.
  2. Change the line styles with linestyle="--".
  3. 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.
Back to the 12-IP index