Python Matplotlib折线图坐标轴刻度自定义设置指南

清欢
清欢
发布时间:2026-10-13| 3人浏览过
原创

本文介绍如何在Python Matplotlib中自定义折线图坐标轴刻度。通过xticks函数可设置整数或时间标签,利用FormatStrFormatter控制小数位数显示。提供完整代码示例,帮助开发者灵活调整图表展示效果,适用于数据分析与可视化场景。

在Python中使用Matplotlib绘制折线图时,有时需要调整坐标轴的刻度显示方式,例如将默认刻度改为整数显示。

具体实现代码如下:

from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
import numpy as np


def std_plot():
 overall_std = [34.369, 21.366, 16.516, 11.151]
 max_std = [36.769, 21.794, 14.390, 4.684]
 plt.figure()
 plt.plot(overall_std, label='average_std')

 plt.plot(max_std, label='max_std')
 plt.legend()
 plt.xlabel('window')
 plt.ylabel('std')
 plt.xticks(range(len(max_std)))
 # plt.gca().xaxis.set_major_formatter(ticker.FormatStrFormatter('%1.1f'))

 plt.show()

std_plot()

通过上述方法,可以自定义X轴刻度的显示样式,例如根据时间序列进行展示。只需调整相关参数即可实现:

plt.xticks(pd.date_range('2014-09-01','2014-09-30'),rotation=90)#设置时间标签显示格式

若希望刻度保留小数点后一位,可采用以下方式:

from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
import numpy as np


def std_plot():
 overall_std = [34.369, 21.366, 16.516, 11.151]
 max_std = [36.769, 21.794, 14.390, 4.684]
 plt.figure()
 plt.plot(overall_std, label='average_std')

 plt.plot(max_std, label='max_std')
 plt.legend()
 plt.xlabel('window')
 plt.ylabel('std')
 # plt.xticks(range(len(max_std)))
 plt.gca().xaxis.set_major_formatter(ticker.FormatStrFormatter('%1.1f'))

 plt.show()


std_plot()

以上关于修改Python Plot折线图坐标轴刻度的方法分享完毕,希望能为读者提供参考,欢迎支持本站。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。