After importing matplotlib.pyplot as plt, we draw line plots with the plt.plot() command.
Here is a code snippet for a simple example of plotting the temperature of the week:
# Import the Matplotlib module
import matplotlib.pyplot as plt
# Use a list to store the daily temperature
t = [22.2,22.3,22.5,21.8,22.5,23.4,22.8]
# Plot the daily temperature t as a line plot
plt.plot(t)
# Show the plot
plt.show()
After you run the code, the following plot will be displayed as the output in the notebook cell:
When a single parameter is parsed, the data values are assumed to be on the y axis, with the indices on the x axis.
Remember to conclude each plot with plt.show(). If you forget this, a plot object will be shown as the output instead of the plot. If you do not overwrite the plot with other plotting commands, you can call plt.show() in the next running cell to display the plot. The following is a screenshot made to illustrate the case:
Also, if you run the plotting commands multiple times before calling plt.show(), multiple plots or plots with unexpected elements (for example, changed color) will appear in the output area the next time you add the line back and run. We can demonstrate this by duplicating the same plotting commands in two cells running consecutively before showing the plot. In the following screenshot, you will see a change in color from the default blue as previously, to brown. This is due to the blue, line plotted with the first command being covered with a second brown line from the second command:
Suppressing function output: Sometimes the plot may show up without calling plt.show(), but the line of the matplotlib object also shows up without giving much useful information. We can put a semicolon (;) at the end of a code line to suppress its input. For instance, in the following quick example, we will not see the Matplotlib object [<matplotlib.lines.Line2D at 0x7f6dc6afe2e8>] appear in the output when we put ; after the plotting command:
To specify a customized x-axis, simply supply it as the first argument to plt.plot(). Let's say we plot the temperatures from the date 11th. We can plot temperatures t against a list of dates d by calling plt.plot(d,t). Here is the result, where you can observe the specified dates on the x axis: