如何增大图表时间刻度间隔?附Python绘图代码求助
问题描述
我有一个读取CSV文件并输出12张图表的函数,但图表底部的时间刻度间隔非常小。我希望将该间隔调整为至少每5秒甚至每1秒显示一次,请问能否在不单独创建figure的前提下实现此需求?
原函数代码
def Gr(): df = pd.read_csv('DataSet.csv',) '''start = df['Time'].iloc[0] start = str(start) start1 = start.replace(':', '-') end = df['Time'].iloc[-1] end = str(end) end1 = end.replace(':', '-') index = pd.date_range(start = start1, end = end1, freq = "S") index = [pd.to_datetime(date, format='%H:%M:%S').date() for date in index] ''' names = ['P', 'Filter', 'Answers', 'step','step2','Comulative', 'Delta_ema','ComulativePOC', 'Delta_P', 'Sum','SpeedUp', 'M' ] features = df[names] features.index = df['Time'] axs = features.plot(subplots=True) cursor = MultiCursor(axs[1].get_figure().canvas, axs) plt.subplots_adjust(wspace=0.19, hspace=0.05, top=0.99, right=0.988, bottom=0.052, left=0.055) plt.show()
问题图示
图表底部时间刻度间隔过密,刻度标签挤在一起难以分辨
解决方案
完全可以不单独创建figure实现需求,核心是把时间索引转为datetime类型,并通过matplotlib的日期工具精准控制刻度间隔:
修改后的代码
import pandas as pd import matplotlib.pyplot as plt from matplotlib.widgets import MultiCursor import matplotlib.dates as mdates def Gr(): df = pd.read_csv('DataSet.csv') # 关键步骤:将Time列转换为datetime格式,让matplotlib识别为时间序列 df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S') names = ['P', 'Filter', 'Answers', 'step','step2','Comulative', 'Delta_ema','ComulativePOC', 'Delta_P', 'Sum','SpeedUp', 'M' ] features = df[names] features.index = df['Time'] axs = features.plot(subplots=True) cursor = MultiCursor(axs[1].get_figure().canvas, axs) # 遍历所有子图,统一设置x轴时间刻度规则 for ax in axs: # 设置刻度间隔:interval=1为每1秒一个刻度,改成5就是每5秒 ax.xaxis.set_major_locator(mdates.SecondLocator(interval=1)) # 设置时间显示格式,仅展示时分秒 ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S')) # 旋转刻度标签,避免横向重叠 plt.setp(ax.get_xticklabels(), rotation=45, ha='right') # 调整底部间距,防止旋转后的标签被截断 plt.subplots_adjust(wspace=0.19, hspace=0.05, top=0.99, right=0.988, bottom=0.15, left=0.055) plt.show()
关键说明
- 时间类型转换:原代码中
Time列是字符串格式,matplotlib无法识别为时间序列,导致刻度自动生成时出现过密问题。转换为datetime后,才能用日期工具控制刻度逻辑。 - 刻度定位器:
mdates.SecondLocator(interval=1)直接指定刻度的时间间隔,按需修改interval参数即可切换1秒/5秒的刻度密度。 - 子图批量设置:因为是多子图布局,需要循环所有
axs对象,确保每个子图的x轴都应用相同的刻度规则。 - 布局调整:旋转标签后底部需要更多空间,所以把
bottom参数从0.052调整为0.15,避免标签被截断。
内容的提问来源于stack exchange,提问作者Genry
相关产品推荐
相关产品推荐

