Several graphs in one picture · Python Programming Class 11–12 | StemPy Lab
Course 1.2·Lesson 4 of 5
Several graphs in one picture
fig, ax = plt.subplots() makes a figure and its axes, and the object style calls the methods of ax, such as ax.plot, ax.set_title, ax.set_xlabel and ax.set_ylabel. plt.subplots with a number of rows and columns gives several axes in one picture, which are used to compare graphs side by side, and fig.tight_layout stops the labels from touching, figsize sets the size, and sharex shares the x axis. Error bars from ax.errorbar show the uncertainty of each point, and for counts the usual size is the square root of the count. ax.set_yscale with log turns an exponential decay into a straight line, which is how decay is tested. fig.savefig saves the picture in a file, and plt.close frees the memory.
about 35 min1 simulation2 practice questions
Lesson 4 of 5Show all lessonsHide
Try the code and the simulations beside the lesson.
What you will be able to do
After this lesson you can
put several graphs side by side in one picture,
use the object style, fig, ax = plt.subplots(),
add error bars and use a log scale, and
save a graph in a file.
Figure and axes
A matplotlib picture has two parts. The figure is the whole sheet. The axes are one plotting area on the sheet, with its own x axis and y axis. A figure can have several axes, side by side or one above the other.
So far, you used plt.plot and plt.title, which work on the "current" axes. When there are several axes, you must say which one you mean. For this, you keep the axes in a variable: fig, ax = plt.subplots(). Then you call the methods of ax. This is the object style, and it is what professionals use.
plt style
object style
plt.plot(x, y)
ax.plot(x, y)
plt.title("...")
ax.set_title("...")
plt.xlabel("...")
ax.set_xlabel("...")
plt.ylabel("...")
ax.set_ylabel("...")
plt.xlim(a, b)
ax.set_xlim(a, b)
plt.legend()
ax.legend()
plt.grid(True)
ax.grid(True)
Two graphs side by side
Predict first. A ball is thrown up at 20 m/s. What is its speed at the top of the path? Then run it.
Two graphs side by side. The left graph, Height, shows a ball rising to about 20 metres at 2 seconds and falling back to the ground at about 4 seconds, in an arch. The right graph, Speed with up as positive, shows a straight line falling from 20 metres per second at the start through 0 at 2 seconds to minus 20 metres per second at about 4 seconds.
For a table of graphs, use more rows and columns. plt.subplots(2, 3) gives 6 axes in a 2 by 3 array, and you reach one with axes[1, 0].
Error bars and the log scale
Two graphs of radioactive counts against time, with error bars. On the left, with a linear scale, the counts fall from 1000 to about 125 in a curve that flattens out. On the right, with a log scale, the same points fall along an almost straight line.
A count of 100 is uncertain by 10 percent; a count of 10,000 by only 1 percent.
Saving a graph
Common mistakes
Mixing the two styles.plt.title after you made several axes works on the last one only. In a picture with several axes, use ax.set_title.
Forgetting tight_layout. The labels overlap.
Putting a log scale on data with zero or negative numbers. The logarithm of zero does not exist.
Showing a point without its error bar when the measurement is uncertain.
Forgetting that ax is an array when subplots has more than one row and column. Use ax[0], or ax[1, 0].
Practice
Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
Warm-up. Open the lab Two panels. You write a function that makes a figure with two graphs.
Build. Open the problem Cooling curve on a log scale and the problem Show it in two panels.
Remember these
fig, ax = plt.subplots(rows, columns) gives a figure and its axes. Call the methods of ax.
fig.tight_layout() keeps the labels apart. figsize sets the size.
ax.errorbar shows the uncertainty. For a count, the usual error is its square root.
A log scale turns an exponential decay into a straight line.
fig.savefig("name.png") saves, and plt.close(fig) frees the memory.
Check yourself
Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
What does plt.subplots(2, 3) give?
What is the usual uncertainty of a count of 400?
What does a straight line on a log graph tell you?
What is the object-style call for the title of the axes ax?
Enroll free in Graphs with matplotlib
Every lesson is open to read. Enrolling also lets you:
Mark lessons done and carry on where you stopped.
Take the tests of this lesson and its course.
Count the course towards the certificate for its chapter.