Python to draw horizontal and vertical lines as dividing lines
When plotting, you often encounter situations where you need to add dividing lines. So, which functions in Python can conveniently draw horizontal or vertical lines? Below are two functions that can easily add horizontal or vertical lines.
1. Using matplotlib.pyplot’s hlines and vlines
######Import required modules
import numpy as np
import matplotlib.pyplot as plt
######This is the butterfly curve part
df = sns.load_dataset('iris')
t = np.arange(0.0, 12*np.pi, 0.01)
x = np.sin(t)*(np.e**np.cos(t) - 2*np.cos(4*t)-np.sin(t/12)**5)
y = np.cos(t)*(np.e**np.cos(t) - 2*np.cos(4*t)-np.sin(t/12)**5)
plt.figure(figsize=(8,6))
plt.plot(x,y,color='blue',linewidth = '3')
#######This is the dividing line part
plt.hlines(0, -3, 3,color="red")#Horizontal line
plt.vlines(0, -2, 3,color="red")#Vertical line
matplotlib.pyplot.hlines(y, xmin, xmax)
represents a horizontal line, with parameters (y-value, starting x-coordinate of the horizontal line, ending x-coordinate of the horizontal line).
matplotlib.pyplot.vlines(y, xmin, xmax)
represents a vertical line, with parameters (x-value, starting y-coordinate of the vertical line, ending y-coordinate of the vertical line).
2. Using matplotlib.pyplot’s axhline and axvline
######Import modules
import numpy as np
import matplotlib.pyplot as plt
######This is the butterfly curve part
df = sns.load_dataset('iris')
t = np.arange(0.0, 12*np.pi, 0.01)
x = np.sin(t)*(np.e**np.cos(t) - 2*np.cos(4*t)-np.sin(t/12)**5)
y = np.cos(t)*(np.e**np.cos(t) - 2*np.cos(4*t)-np.sin(t/12)**5)
plt.figure(figsize=(8,6))
plt.plot(x,y,color='blue',linewidth = '3')
#######This is the dividing line part
plt.axhlines(0, -3, 3,color="red")#Horizontal line
plt.axvlines(0, -2, 3,color="red")#Vertical line
matplotlib.pyplot.axhlines(y, xmin, xmax)
represents a horizontal line, with parameters (y-value, starting x-coordinate of the horizontal line, ending x-coordinate of the horizontal line).
matplotlib.pyplot.axvlines(y, xmin, xmax)
represents a vertical line, with parameters (x-value, starting y-coordinate of the vertical line, ending y-coordinate of the vertical line).
Summary
matplotlib.pyplot.hlines
and matplotlib.pyplot.axhlines
can both draw horizontal lines, but as we can see from the figure, there are differences. The hline
line does not touch the axis, while axhline
does.
Similarly, vlines
and axvlines
are both vertical lines; one does not touch the axis, and the other does.
Please choose different matplotlib.pyplot
functions as needed.
- 原文作者:春江暮客
- 原文链接:https://www.bobobk.com/en/213.html
- 版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可,非商业转载请注明出处(作者,原文链接),商业转载请联系作者获得授权。