You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将图表横轴设为hh:min格式并处理Excel时间数据?

解决方法

这里用Python的pandas和matplotlib来实现需求,步骤如下:

  1. 将Excel格式时间转换为标准datetime类型
    Excel的时间数值是从1900年1月1日开始的天数(小数部分对应时分秒),用pandas可直接转换:

    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib.dates import DateFormatter, HourLocator
    
    # 假设数据存储在DataFrame df中,时间列名为'time',张力列名为'tension'
    df['time'] = pd.to_datetime(df['time'], origin='1900-01-01', unit='D')
    
  2. 绘制图表并自定义横轴样式
    先绘制折线图,再设置横轴的刻度格式与范围:

    fig, ax = plt.subplots(figsize=(10,6))
    ax.plot(df['time'], df['tension'])
    
    # 设置横轴时间显示格式为HH:MM
    date_format = DateFormatter('%H:%M')
    ax.xaxis.set_major_formatter(date_format)
    
    # 强制锁定横轴起止时间为19:03
    start_time = df['time'].min().floor('D') + pd.Timedelta(hours=19, minutes=3)
    end_time = df['time'].max().floor('D') + pd.Timedelta(hours=19, minutes=3)
    ax.set_xlim(start_time, end_time)
    
    # 设置刻度间隔(示例为每2小时一个刻度,可按需调整)
    ax.xaxis.set_major_locator(HourLocator(interval=2))
    
    # 添加轴标签与标题
    ax.set_xlabel('时间')
    ax.set_ylabel('张力')
    plt.title('张力随时间变化')
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.show()
    
  3. 细节调整提示

    • 如果时间转换后与实际不符,检查Excel版本:旧版Excel可能用1904年作为时间原点,只需把origin='1900-01-01'改成origin='1904-01-01'
    • 刻度间隔可通过HourLocator(interval=N)修改N值,比如设为1就是每小时一个刻度

内容的提问来源于stack exchange,提问作者Camille

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 21:18:14