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

Matplotlib Pyplot绘图中数据点间无连线问题求助

问题原因与解决方案

你的问题出在使用字符串类型的时间标签作为x轴。当绘制多列数据时,matplotlib将字符串视为分类变量,无法正确识别数据点的连续顺序,导致连线消失;而单列数据时能正常显示,是因为matplotlib对单一分类序列的处理逻辑特殊。

修复方案

改用**数值类型的时间(当日秒数)**作为x轴绘图,同时保留时间字符串作为刻度标签。这样matplotlib能正确识别数据点的连续顺序,从而绘制出完整连线。

修正后的代码

daily_dfs = [group for _, group in every_df.resample("D")]
    
num_dfs = len(daily_dfs)
try:
    fig, axes = plt.subplots(num_dfs, 1, figsize=(10, num_dfs * 5), sharex=True, sharey=True)
except ValueError:
    break
if num_dfs == 1:
    axes = [axes]

lines = []
labels = []

for i, daily_df in enumerate(daily_dfs):
    ax = axes[i]
    # 计算当日秒数(数值型x轴)
    seconds_since_start_of_day = daily_df.index.map(lambda t: t.hour * 3600 + t.minute * 60 + t.second)
    time_of_day = daily_df.index.strftime('%H:%M')
    
    # 设置x轴刻度:每20个数据点显示一个标签
    tick_indices = range(0, len(time_of_day), 20)
    # 用当日秒数定位刻度位置,时间字符串作为显示标签
    ax.set_xticks([seconds_since_start_of_day.iloc[i] for i in tick_indices])
    ax.set_xticklabels([time_of_day[i] for i in tick_indices])
    
    for column in daily_df.columns:
        # 改用数值型的当日秒数作为x轴
        line, = ax.plot(seconds_since_start_of_day, daily_df[column], "o-", label=column)
        if i == 0:
            lines.append(line)
            labels.append(column)
    
    ax.set_title(daily_df.index[0].strftime('%A'))
    ax.set_ylabel(parameter)
    if i < num_dfs - 1:
        ax.label_outer()

axes[-1].set_xlabel('Time')
fig.legend(lines, labels, loc="upper right", bbox_to_anchor=(1, 1), fontsize='large')
plt.tight_layout()

关键修改点

  1. 将ax.plot的x参数从time_of_day(字符串)改为seconds_since_start_of_day(数值),让matplotlib识别连续的时间轴。
  2. 调整刻度设置:用数值位置定位刻度,同时保留时间字符串作为显示标签,兼顾可读性和绘图逻辑。

修改后,无论单列还是多列数据,matplotlib都会正确绘制数据点之间的连线。

内容的提问来源于stack exchange,提问作者Tim Bgel Timster2k

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 18:06:00