ByteBoard Notes Notes

Plot the monthly sales of two products on one line chart and save it as a PNG file

Informatics Practices XII · Experiment 20 of 38 · Pandas

12-IPMatplotlib programs
Expt. No.20
Page No.40

Two-line sales chart, saved as PNG

Aim

To write a Python program that plots the monthly sales of two products on one line chart with labels, title and legend, and saves the chart as a PNG file.

Concepts used

Algorithm

  1. Store the months and the sales of two products in lists.
  2. Plot both lines with labels.
  3. Add axis labels, a title and a legend.
  4. Save the chart with plt.savefig("sales.png"), then show it.

Program

# Monthly sales of two products, saved as an image import matplotlib.pyplot as plt months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]laptops = [120, 135, 150, 145, 170, 190]tablets = [90, 95, 110, 130, 125, 140] plt.plot(months, laptops, label="Laptops")plt.plot(months, tablets, label="Tablets")plt.xlabel("Month")plt.ylabel("Units sold")plt.title("Sales: January to June")plt.legend()plt.savefig("sales.png")print("Chart saved as sales.png")plt.show()

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python plot_sales_savefig.py
Chart saved as sales.png
Figure 1
Line chart of units sold from January to June: laptops rise from 120 to 190 and tablets from 90 to 140, with laptops ahead every month.

✓ Printed by running this program, not typed by hand.

Result

Both products sold more in June than in January, and laptops were ahead in every month. The chart was saved as sales.png in the program's folder before it was shown.

Viva voce: what the examiner may ask

01Why is savefig() called before show()?

After show() the figure is closed, so saving afterwards would give an empty image.

02Which file formats can savefig() use?

PNG, JPG, PDF and SVG, chosen by the file extension.

03Why is a line chart used here?

The sales change over time (months), which a line shows well.

Variations for the lab test

  1. Save the chart as a PDF.
  2. Add a third product.
  3. Plot the difference between laptop and tablet sales.
! Common mistake Calling plt.savefig() after plt.show() saves a blank image.
Back to the 12-IP index