Charts with matplotlib
Not met yet
Charts start with import matplotlib.pyplot as plt, and fig, ax = plt.subplots() gives a figure, the whole picture, and an axes, the framed box with scales that the data is drawn in. ax.plot(x, y) adds a line, ax.scatter(x, y) adds dots and ax.bar(names, heights) adds bars; every call adds to the same axes, and plot given a single list draws it as heights against 0, 1, 2 and so on. ax.set_xlabel, ax.set_ylabel and ax.set_title name things, ax.set_ylim(bottom=0) starts the scale at 0, and a label= on each line shows up only once you call ax.legend(). figsize=(8, 4) is in inches, not pixels. The shorter plt.plot and plt.xlabel do the same jobs on whichever axes was made last, and plt.show() puts the picture on the page.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks each call to plot replaces the line already on the axes, rather than adding another.
- Thinks plot with one list uses it as the x values, when it is taken as the y values against 0, 1, 2 and so on.
- Thinks giving a line a label= is enough to show a key, without calling legend().
- Thinks figsize is measured in pixels, when it is in inches.
- Thinks an axes has pyplot's method names, ax.xlabel and ax.title, rather than ax.set_xlabel and ax.set_title.