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

如何在同一时间轴图表中绘制DataFrame不同Element的Q值

解决方案

核心问题修正:将Date列转为datetime类型

你的两次尝试失败的核心原因是Date列是字符串格式,matplotlib无法将其识别为连续时间轴,导致x轴显示混乱。首先必须把Date列转换成datetime类型:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# 构建你的DataFrame
data = [
    ['A', '24/10/2021 17:16', 400],
    ['B', '24/10/2021 18:59', 210],
    ['A', '26/10/2021 18:42', 325],
    ['A', '26/10/2021 19:44', 589],
    ['B', '29/10/2021 14:23', 251],
    ['A', '01/11/2021 9:12', 578],
    ['B', '02/11/2021 21:30', 321],
    ['A', '04/11/2021 18:25', 248],
    ['B', '05/11/2021 10:29', 854],
    ['A', '05/11/2021 10:26', 968],
    ['A', '07/11/2021 18:10', 852],
    ['A', '09/11/2021 16:35', 425],
    ['B', '09/11/2021 21:55', 752],
    ['A', '11/11/2021 18:41', 385],
    ['B', '13/11/2021 11:15', 658],
    ['A', '14/11/2021 18:17', 229],
    ['B', '16/11/2021 22:36', 258],
    ['A', '17/11/2021 17:05', 359],
    ['A', '18/11/2021 16:39', 210],
    ['B', '19/11/2021 15:41', 583]
]
df = pd.DataFrame(data, columns=['Element', 'Date', 'Q'])

# 转换Date列为datetime类型,匹配原格式
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y %H:%M')

方法1:Pandas分绘共享轴

# 拆分数据
dfA = df[df['Element'] == 'A']
dfB = df[df['Element'] == 'B']

# 创建画布与轴
fig, ax = plt.subplots(figsize=(12,6))

# 绘制A的散点并添加标签
dfA.plot.scatter(x='Date', y='Q', label='A', color='blue', ax=ax)
# 绘制B的散点,共享同一轴
dfB.plot.scatter(x='Date', y='Q', label='B', color='red', ax=ax)

# 设置时间轴刻度与格式
ax.xaxis.set_major_locator(mdates.DayLocator(interval=2))  # 每2天显示一个刻度
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))

# 自动旋转x轴标签避免重叠
plt.gcf().autofmt_xdate()

# 添加标题与轴标签
ax.set_title('Q值随时间变化(A vs B)')
ax.set_xlabel('日期')
ax.set_ylabel('Q值')

# 显示图例
ax.legend()

plt.show()

方法2:Seaborn一键分组绘制

用seaborn可更简洁地实现分组绘图,自动生成对应图例:

import seaborn as sns

plt.figure(figsize=(12,6))
sns.scatterplot(data=df, x='Date', y='Q', hue='Element', palette={'A':'blue', 'B':'red'})

# 设置时间轴格式
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=2))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))

plt.gcf().autofmt_xdate()
plt.title('Q值随时间变化(A vs B)')
plt.xlabel('日期')
plt.ylabel('Q值')
plt.legend(title='Element')

plt.show()

关键说明

只有将Date转为datetime类型,matplotlib才能识别为连续时间轴,确保A、B的数据点在正确的时间位置对齐,实现共享x轴的需求。两种方法均可达成目标,可根据使用习惯选择。

内容的提问来源于stack exchange,提问作者Karl.os

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:20:48