
上QQ阅读APP看书,第一时间看更新
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:
