Worksheets › Class 12 › Plotting Data using Matplotlib › Cheat sheet
Class 12 Plotting Data using Matplotlib: cheat sheet
CBSE Informatics Practices. Drawing charts with Matplotlib’s pyplot: line plots, bar charts and histograms, labels, titles and legends, colours and styles, saving a chart, and plotting straight from pandas.
Key ideas
- Import the module with import matplotlib.pyplot as plt; plt.show() displays the chart.
- plt.plot(x, y) draws a line chart for a trend over time; plt.bar(x, h) draws bars for categories (plt.barh for horizontal ones); plt.hist(data, bins=…) shows how many values fall in each interval.
- plt.pie() shows each part’s share of a whole and plt.scatter() one dot per pair of values.
- plt.xlabel(), plt.ylabel() and plt.title() name the axes and the chart; label= names a line and plt.legend() lists the names.
- Arguments change the look: color='green', marker='o', linestyle='dashed', linewidth=3, markersize=10, edgecolor='black'.
- In a histogram each bin includes its left edge but not its right, except the last bin, which includes both; bins=5 splits the range into 5 equal intervals, and the bars touch.
- plt.savefig('chart.png') saves the chart; call it before plt.show(). A DataFrame draws itself with df.plot(), the chart chosen by kind='line', 'bar', 'barh' or 'hist'.
Remember
| Line and bar charts | plt.plot(x, y, marker='o'); plt.bar(x, h); plt.barh(x, h) |
| Histogram | plt.hist(data, bins=[10, 20, 30, 40]) |
| Bins 10–20, 20–30, 30–40 | each takes its left edge; the last also takes 40 |
| Names | plt.xlabel('Month'); plt.ylabel('Sales'); plt.title('Weekly Sales') |
| Legend | plt.plot(m, a, label='Shop A'), then plt.legend() |
| pandas bars | df.plot(kind='bar', x='Name', y=['Q1', 'Q2']): 2 bars for each row |
Watch out
- Putting a value on a bin edge into the bin on its left: 20 belongs to 20–30.
- Calling plt.legend() without giving the lines a label.
- Calling savefig() after show(), which can save an empty picture.
- Using a bar chart for intervals of continuous data: that needs a histogram.
Worked example
Write the height of each bar of this histogram. import matplotlib.pyplot as plt data = [22, 61, 22, 80, 50, 40, 70, 30, 44, 47, 75, 80, 31] plt.hist(data, bins=[20, 40, 60, 80]) plt.show() (a) 20–40 (b) 40–60 (c) 60–80
Working: each bin includes its left edge; the last bin includes 80 too
Answer: (a) 4; (b) 4; (c) 5
Practise Plotting Data using Matplotlib
Revise with this page, then practise: every Plotting Data using Matplotlib sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.