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

Matplotlib如何正确显示包含分钟、秒的时间跨度数据?

解决方案

核心思路是分两步处理60进制的时间格式:先把分:秒格式的字符串转换为十进制的连续数值(比如十进制分钟数/总秒数)保证绘图比例正确,再自定义y轴刻度格式把数值转换回分:秒格式保证可读性。


步骤1:预处理时间数据

先写一个辅助函数,把你数据里的XX:XX格式的时间字符串转换为十进制分钟数,避免60进制带来的数值比例错误:

def time_str_to_min(time_str):
    # 输入格式为 "分:秒",输出对应的十进制分钟数
    minutes, seconds = map(int, time_str.split(":"))
    return minutes + seconds / 60

# 对DataFrame的时间列做转换
df["MinTime_num"] = df["MinTime"].apply(time_str_to_min)
df["MaxTime_num"] = df["MaxTime"].apply(time_str_to_min)

步骤2:调整可视化代码

修改你的绘图函数,使用转换后的数值列绘图,同时自定义y轴刻度的显示格式,把十进制数值转回分:秒格式:

import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import FuncFormatter

# 定义y轴刻度格式化函数:把十进制分钟数转回 分:秒 字符串
def format_y_ticks(x, pos):
    minutes = int(x)
    seconds = int(round((x - minutes) * 60))
    # 处理秒数进位的边界情况
    if seconds == 60:
        minutes += 1
        seconds = 0
    return f"{minutes}:{seconds:02d}"

def show_performance_stats(df):
    sns.set(style='darkgrid')
    sns.set(font_scale=1)
    plt.rcParams["figure.figsize"] = (6.5,4) 

    # 改用转换后的数值列绘图
    plt.plot(df['MinTime_num'], 'bo', label="Min Time")
    plt.plot(df['MaxTime_num'], 'go', label="Max Time")

    # 标签设置,修正了原代码的拼写错误
    plt.title("Performance for each category")
    plt.ylabel("Time (min:sec)")
    plt.legend()
    plt.xticks([0, 1, 2, 3], df['Models']) 
    # 保留原刻度间隔,自定义显示格式
    plt.yticks([0, 10, 20, 30, 40])
    plt.gca().yaxis.set_major_formatter(FuncFormatter(format_y_ticks))

    chart = Chart.get_graph_file("Performance")
    plt.savefig(chart)   
    plt.close()

说明

如果你的时间跨度更大,也可以把时间转换为总秒数做计算,只要对应修改预处理和y轴格式化的逻辑即可,核心逻辑都是统一的:计算用十进制数值保证比例正确,显示用60进制格式符合阅读习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:36:01