Matplotlib 中的次要刻度
本篇文章教你如何在 Matplotlib 中使用和格式化次要刻度。Matplotlib 是一个 Python 数据可视化绘图库。
在使用绘图之前,我们需要设置我们的脚本以使用该库。我们首先导入 Matplotlib,然后从 random
模块加载 randrange
函数以快速生成一些数据。
请记住,你的输出看起来会有所不同。
代码示例:
import matplotlib.pyplot as plt
from random import randrange
data_1 = [randrange(0, 10) for _ in range(0, 10)]
data_2 = [randrange(0, 10) for _ in range(0, 10)]
在 Matplotlib 中激活 Minor Ticks
在 Matplotlib 中激活次要刻度就像调用 pyplot.minorticks_on()
方法一样简单。
代码示例:
plt.plot(data_1)
plt.minorticks_on()
请记住,由于随机生成的数字,你的绘图看起来会有所不同。如你所见,较大的编号之间没有次要刻度。
输出:
Matplotlib 中的样式次要刻度
我们还可以设置次要/主要刻度的样式,使其看起来更符合我们的喜好。我们使用 pyplot.tick_params()
方法来做到这一点。
在以下示例中,我应用了一些样式选项。
代码示例:
# For the X Axis
plt.tick_params(
axis="x",
which="minor",
length=10,
color="r")
# For the Y Axis
plt.tick_params(
axis="y",
which="major",
length=10,
color="g",
labelrotation=45.0)
plt.show()
该函数采用 axis
参数,该参数确定以下样式应用于哪个轴,而 which
参数确定它是应用于主要刻度还是次要刻度。现在有很多选项来设置你的刻度。
输出:
底部的次要刻度现在是红色的并且在上面的输出中更长。侧面的刻度是绿色的,它们的标签旋转了 45 度。
现在你知道了如何在 Matplotlib 中启用和设置次要刻度。
完整代码:
import matplotlib.pyplot as plt
from random import randrange
data_1 = [randrange(0, 10) for _ in range(0, 10)]
plt.plot(data_1)
plt.minorticks_on()
# For the X Axis
plt.tick_params(
axis="x",
which="minor",
length=10,
color="r")
# For the Y Axis
plt.tick_params(
axis="y",
which="major",
length=10,
color="g",
labelrotation=45.0)
plt.show()
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串