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.
| 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 |
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