如何在 matplotlib 中绘制虚线?
先决条件: Matplotlib
在本文中,我们将了解如何在 matplotlib 中绘制虚线。 Matplotlib 虚线是一种特殊样式的折线图,它借助 linestyle 来表示 X 轴和 Y 轴的关系——虚线,我们还可以为每条线设置不同的颜色和不同的线宽。让我们通过以下不同的示例来理解它:
要绘制虚线数据点:
Syntax: matplotlib.pyplot.plot(x, y, linestyle=’dashed’)
- x: X-axis points on the line.
- y: Y-axis points on the line.
- linestyle: Change the style of the line.
- linewidhth: set width of a dash line.
示例 1:在 matplotlib 中绘制虚线
要绘制虚线,我们将创建数据集,然后使用上述语法绘制虚线数据点。
Syntax: plt.plot(linestyle=’dashed’)
Python3
# Import libraries
import matplotlib.pyplot as plt
# Define Axes
x_points = [1.5, 2.6, 3.5, 4, 9]
y_points = [3.25, 6.3, 4.23, 1.35, 3]
# Plot a graph
plt.plot(x_points, y_points, linestyle='dashed')
# Display graph
plt.show()
Python3
# Import libraries
import matplotlib.pyplot as plt
# Define Axes
X = [1.5, 2.6, 3.5, 4, 9]
Y = [3.25, 6.3, 4.23, 1.35, 3]
# Plot a graph
plt.plot(X, Y, linestyle='--', color='gold')
# Display graph
plt.show()
Python3
# Import libraries
import matplotlib.pyplot as plt
# Define Axes
X = [1.5, 5.6, 3.5, 4, 9]
Y1 = [1, 4, 3, 4, 5]
Y2 = [6, 7, 4, 9, 10]
# Plot a graph
plt.plot(X, Y1, linestyle='dashed', color='black')
plt.plot(X, Y2, linestyle='dashed',
color='red', linewidth=4)
# Display graph
plt.show()
输出:
示例 2:在 matplotlib 中自定义颜色虚线
为了自定义,我们将使用颜色属性。
Syntax: plt.plot(linestyle=’–’, color=’gold’)
Python3
# Import libraries
import matplotlib.pyplot as plt
# Define Axes
X = [1.5, 2.6, 3.5, 4, 9]
Y = [3.25, 6.3, 4.23, 1.35, 3]
# Plot a graph
plt.plot(X, Y, linestyle='--', color='gold')
# Display graph
plt.show()
输出:
示例 3:在 matplotlib 中自定义数据点虚线
linewidth 属性可用于设置数据点之间的宽度。
Syntax: plt.plot(linestyle=’dashed’, linewidth= int)
Python3
# Import libraries
import matplotlib.pyplot as plt
# Define Axes
X = [1.5, 5.6, 3.5, 4, 9]
Y1 = [1, 4, 3, 4, 5]
Y2 = [6, 7, 4, 9, 10]
# Plot a graph
plt.plot(X, Y1, linestyle='dashed', color='black')
plt.plot(X, Y2, linestyle='dashed',
color='red', linewidth=4)
# Display graph
plt.show()
输出