Course 1.2Lesson 1 of 5
A graph shows what a table of numbers hides. matplotlib.pyplot, imported as plt, draws it: plt.plot with an array of x values and an array of y values joins the points with a line, and plt.title, plt.xlabel and plt.ylabel name the graph and the axes, with the units. A format such as o-, s-- or a colour changes the markers and the line, a label with plt.legend names each line when there are several, and plt.grid adds a grid. Every plot call adds to the same picture until plt.show. The two arrays must have the same length, otherwise there is a ValueError. A good graph has a title, labelled axes with units, and a legend when it has more than one line.
Try the code and the simulations beside the lesson.
After this lesson you can
plt.plot,Here are six numbers: 0, 150, 330, 480, 650, 800. Do they tell you anything? Now see them on a graph: the line rises, and you can see how fast, and whether the speed changes. A graph turns a table of numbers into a picture that a person understands in a second. Every science report has graphs, and they are the first thing that a reader looks at.
The library for graphs in Python is matplotlib. You use its part called pyplot, and by custom you import it as plt:
On this site, matplotlib is ready. The first time that your code uses it, the site needs a few seconds to load it. The graph appears under the output of your program.
Predict first. Will the line go up or down? Will it be a straight line? Then run it.
The line rises from 0 to 800 metres. In the first minute the cyclist goes 150 m, and in the last minute 150 m again. Between them there is a faster minute, from 2 to 3 minutes, when the cyclist rode 180 m.
The last line of the program prints a number. Asha is 260 m ahead after 5 minutes. On the graph, this is the gap between the two lines at the right end.
A good graph says what each axis is and in which unit. Without labels, nobody can read it, however nice it looks.
Making these a habit is a large part of the skill.
plt.plot([1, 2, 3], [4, 5]) gives a ValueError: x and y must have the same first dimension.plt.legend() shows nothing useful if the lines have no label.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:
plt.plot(x, y) joins the points. x comes first.plt.title, plt.xlabel and plt.ylabel name the graph. Write the unit."o-" sets the markers and the line. Use label and plt.legend() for several lines.plt.plot adds a line to the same picture.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
"s--" mean?plt.plot([1, 2, 3], [4, 5])?plt.plot(a, b)?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.