Matplotlib 简明教程
Matplotlib - Plotting with Keywords
通过关键字作图通常是指使用特定的单词或命令定制和控制如何在绘图或图表中显示数据。
想象一下您有一些数据,例如一周内不同城市的温度。您希望创建一个图形来显示此数据,但您还希望使其外观精良且内容丰富。通过关键字作图可以让您做到这一点。
您可以使用关键字或命令告诉作图软件您想要什么,而不是手动指定绘图的每一个小细节,比如线条颜色、轴标签或点的大小。
例如,您可能会使用“color”这样的关键字,后跟一个特定的颜色名称来更改绘图中线条的颜色。或者,您可以使用“xlabel”和“ylabel”分别给 x 轴和 y 轴添加标签。
Plotting with Keywords in Matplotlib
使用 Matplotlib 创建绘图时,您可以使用关键字来控制绘图的各个方面,如颜色、线条样式、标记样式、标签、标题以及许多其他属性。您应该使用描述性关键字指定这些属性,而不是直接提供数值或配置。
例如,给 x 轴和 y 轴添加标签,您可以分别使用“xlabel”和“ylabel”关键字。
Plotting with Keyword "Color"
在 Matplotlib 中绘图时,可以使用“color”关键字参数指定要绘制的元素的颜色。可以使用多种方式指定颜色−
-
Named Colors − 您可以使用“red”、“blue”、“green”等常见颜色名称指定颜色。
-
Hexadecimal Colors − 您可以使用十六进制颜色代码(例如“#FF5733”)指定精确颜色。
-
RGB or RGBA Colors − 您可以使用 RGB 或 RGBA 值指定颜色,其中 R 代表红色,G 代表绿色,B 代表蓝色,A 代表 alpha(不透明度)。
Example
在以下示例中,我们将创建一个线条图,其中线条颜色使用“color”关键字更改为红色 −
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Changing line color to red
plt.plot(x, y, color='red')
# Customizing Plot
plt.title('Line Plot with Red Color')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Displaying Plot
plt.show()
以下是上面代码的输出: -
Plotting with Keyword "marker"
在 Matplotlib 中,通过关键字“marker”绘图用于指定符号或标记,这些符号或标记用于表示绘图上各个数据点。
在 Matplotlib 中创建散点图或折线图时,每个数据点都可以由标记表示,这是一个小符号或形状。“marker”关键字允许选择这些标记的形状、大小和颜色。常见的标记选项包括圆圈、正方形、三角形和圆点。
Example
在这里,我们使用“marker”关键字在折线图上的数据点处添加圆形标记 −
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Adding circle markers
plt.plot(x, y, marker='o')
# Customizing Plot
plt.title('Line Plot with Circle Markers')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Displaying Plot
plt.show()
执行上述代码,我们将得到以下输出 −
Plotting with Keyword "linestyle"
在 Matplotlib 中,通过关键字“linestyle”绘图用于指定连接绘图中数据点的线条的样式。
在 Matplotlib 中创建折线图时,每个数据点都由一条线连接。“linestyle”关键字允许选择这些线的样式。常见的线条样式选项包括实线、虚线、点线和点划线。您可以分别使用字符串“-”、"--"、":"和"-."指定这些样式。
Example
现在,我们使用“linestyle”关键字将线型更改为“dashed”−
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Changing line style to dashed
plt.plot(x, y, linestyle='--')
# Customizing Plot
plt.title('Line Plot with Dashed Line Style')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Displaying Plot
plt.show()
执行上面的代码后,我们得到以下输出: -
Plotting with Keyword "grid"
在 Matplotlib 中,使用关键字“grid”绘图可将网格线添加到您的绘图中。网格线是水平和垂直线,有助于在绘图中直观地对齐数据点。
“grid”关键字允许您控制网格线是否显示在绘图中。您可以指定是否需要沿着 x 轴、y 轴或两个轴绘制网格线。启用网格线时,它们将显示为跨越绘图区域并形成网格状图案的虚线。
Example
在以下示例中,我们使用“grid”关键字向绘图中添加一个网格 −
import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Plotting
plt.plot(x, y)
# Customizing Plot
plt.title('Line Plot with Grid')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Adding grid
plt.grid(True)
# Displaying Plot
plt.show()
执行上述代码,我们将得到以下输出 −