- Matplotlib for Python Developers
- Aldrin Yim Claire Chung Allen Yu
- 419字
- 2021-08-27 18:48:20
Line plot
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:

- 現代C++編程:從入門到實踐
- Advanced Machine Learning with Python
- 軟件項目估算
- Java程序設計實戰教程
- Unity 2020 Mobile Game Development
- 實戰Java程序設計
- Java面向對象程序開發及實戰
- HTML5游戲開發案例教程
- Functional Programming in JavaScript
- JSP開發案例教程
- Python完全自學教程
- Java EE 7 Performance Tuning and Optimization
- ASP.NET程序開發范例寶典
- JavaScript動態網頁編程
- Instant Debian:Build a Web Server