- Mastering Matplotlib 2.x
- Benjamin Walter Keller
- 230字
- 2021-06-10 19:29:11
Adding horizontal and vertical lines
We will begin by importing our required libraries, as shown:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
# Set up figure size and DPI for screen demo
plt.rcParams['figure.figsize'] = (6,4)
plt.rcParams['figure.dpi'] = 150
- We will create the simple sine plot that we saw in Chapter 1, Heavy Customization, as follows:
# Adding a horizontal and vertical line
nums = np.arange(0,10,0.1)
plt.plot(nums, np.sin(nums))
We will get the following output:

- Now, to add an annotation, say, a line that splits the region between stuff above and below 0.5, add a horizontal line using axhline(0.5), as shown here. ax stands for the x axis and gives a value in the y co-ordinate for the horizontal line:
# Adding a horizontal and vertical line
nums = np.arange(0,10,0.1)
plt.plot(nums, np.sin(nums))
plt.axhline(0.5)
We will get the following output:
- To color this horizontal line red, insert the following code:
# Adding a horizontal and vertical line
nums = np.arange(0,10,0.1)
plt.plot(nums, np.sin(nums))
plt.axhline(0.5, color='r')
We will get the following output:

- To add a vertical line right at the first maximum, input pi/2 and color this red, along with a dashed line:
# Adding a horizontal and vertical line
nums = np.arange(0,10,0.1)
plt.plot(nums, np.sin(nums))
plt.axhline(0.5, color='r')
plt.axvline(np.pi/2., color='r', linestyle='--')
Here we can see axv for the vertical line instead of axhline:

推薦閱讀
- 大數據管理系統
- TestStand工業自動化測試管理(典藏版)
- Java開發技術全程指南
- Learning Social Media Analytics with R
- 大數據技術入門(第2版)
- 讓每張照片都成為佳作的Photoshop后期技法
- 大數據處理平臺
- Hybrid Cloud for Architects
- Ceph:Designing and Implementing Scalable Storage Systems
- 計算機網絡安全
- Apache Superset Quick Start Guide
- The Python Workshop
- Hadoop應用開發基礎
- 網絡管理工具實用詳解
- 人工智能云平臺:原理、設計與應用