Plot the monthly sales of two products on one line chart and save it as a PNG file
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
- Store the months and the sales of two products in lists.
- Plot both lines with labels.
- Add axis labels, a title and a legend.
- 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
✓ 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
- Save the chart as a PDF.
- Add a third product.
- Plot the difference between laptop and tablet sales.
! Common mistake Calling
plt.savefig() after plt.show() saves a blank image.