Python Matplotlib 绘图:设置 X 轴刻度和图例位置
Python Matplotlib 绘图:设置 X 轴刻度和图例位置
本教程将解释如何在 Python Matplotlib 库中使用 plt.xticks() 和 plt.legend() 函数设置 X 轴刻度和图例位置。
代码示例
import matplotlib.pyplot as plt
import numpy as np
# 假设数据
lr1train = [ ... ] # 训练数据 1
lr2train = [ ... ] # 训练数据 2
lr1test = [ ... ] # 测试数据 1
lr2test = [ ... ] # 测试数据 2
# 绘制图形
plt.figure(figsize=(6, 6))
plt.plot(np.linspace(0.05, 1, 19), lr1train, color='blue', label='lr1train')
plt.plot(np.linspace(0.05, 1, 19), lr2train, color='green', label='lr2train')
plt.plot(np.linspace(0.05, 1, 19), lr1test, color='orange', label='lr1test')
plt.plot(np.linspace(0.05, 1, 19), lr2test, color='red', label='lr2test')
# 设置 X 轴刻度
plt.xticks(np.linspace(0.05, 1, 19))
# 添加图例
plt.legend(loc=4) # 图例的位置,4 在右下角
plt.show()
代码解释
-
plt.xticks(np.linspace(0.05, 1, 19))- 设置 X 轴刻度。
np.linspace(0.05, 1, 19)生成一个等差数列,从 0.05 到 1,共 19 个数,作为 X 轴刻度。
-
plt.legend(loc=4)- 添加图例。
loc=4表示将图例放置在右下角。
通过使用这些函数,你可以轻松地自定义 Matplotlib 图形中的 X 轴刻度和图例位置,使你的图形更具可读性和信息量。
原文地址: https://www.cveoy.top/t/topic/f1wN 著作权归作者所有。请勿转载和采集!