A table of numbers hides what a graph shows at once. In this course you draw line graphs with plot, add titles, labels with units, legends and grids, and draw the graph of any formula with linspace. You choose between a line graph, a scatter plot, a bar chart and a histogram, and learn to read each one. You put several graphs in one picture with subplots, add error bars, use a log scale to recognise an exponential decay, and save a graph in a file. A project turns the measured positions of a toy car into the graphs of its speed and acceleration. The practice runs your code and looks at the graphs that you draw.
5 lessons, about 2 h 50 min5 simulations10 problems10 practice questionsPython in every lesson
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.
To draw the graph of a function, make an array of x values with np.linspace, calculate y from the formula for the whole array, and plot the two. More points give a smoother curve, because plt.plot joins the points with straight pieces, so a curve needs about 100 or more. Several curves can share one graph with labels and a legend. Angles for sine and cosine are changed to radians with np.deg2rad. plt.xlim and plt.ylim set the range, plt.axhline and plt.axvline draw the axes, plt.xticks chooses the ticks, plt.plot with a marker shows special points, and plt.annotate writes a note at a point. The meeting points of two graphs are the solutions of an equation, and np.roots finds the roots of a polynomial.
Different questions need different graphs. A line graph shows how one measurement changes with another, such as time. A scatter plot, plt.scatter, shows two measurements of each person or object as one dot, and colour or size can show a third measurement. np.corrcoef gives the correlation, a number between minus 1 and 1, and a strong correlation is not proof that one thing causes the other. A bar chart, plt.bar or ax.bar, compares amounts in separate groups, and ax.bar_label writes the numbers. A histogram, plt.hist, shows how many measurements fall in each bin, and it shows the centre and the spread of a measurement. np.histogram gives the same counts as numbers.
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.
A project that uses the whole chapter: a toy car is measured at its position each second, and the arrays give its speed and acceleration. np.diff of the positions divided by np.diff of the times gives the speed in each second, and the same step on the speeds gives the acceleration, each at the middle of its interval. Three graphs stacked with sharex show position, speed and acceleration against the same time axis. The slope of the position graph is the speed, and the slope of the speed graph is the acceleration. The car speeds up at 1.6 metres per second squared for about 5 seconds, then cruises at 8 metres per second, and the distance in the last 5 seconds is 40 metres, which equals the speed times the time.
Log in to join the discussion.
Loading…