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

如何修正Plotly折线图中柬埔寨数据未按时间序列排序的问题

解决Plotly折线图按时间序列异常连接的问题

问题场景

现有如下结构的Pandas DataFrame:

import pandas as pd
import plotly.express as px

country = ['Cambodia',
 'Cambodia',
 'Cambodia',
 'Cambodia',
 'Cambodia',
 'Lao PDR',
 'Lao PDR',
 'Lao PDR',
 'Lao PDR']

month_year = ['2020-Aug',
 '2020-Dec',
 '2020-May',
 '2020-Oct',
 '2021-Mar',
 '2020-Jul',
 '2021-Mar',
 '2021-May',
 '2021-Nov']

count = [5, 4, 4, 4, 2, 6, 4, 4, 6]

intermediate_dictionary = {'country':country, 'month_year':month_year, 'count':count}
df3 = pd.DataFrame(intermediate_dictionary)

指定有序年月列表后绘制折线图:

ordered_months = ["2020-May", "2020-Jul", "2020-Aug", "2020-Oct", "2020-Dec", "2021-Mar",
      "2021-May", "2021-Nov"]

fig = px.line(df3, x="month_year", y="count", color='country', symbol='country')
fig.update_xaxes(categoryarray= ordered_months)
fig.show()

运行后发现柬埔寨的折线未按预期时间序列(2020-May→2020-Aug→2020-Oct→2020-Dec→2021-Mar)连接,出现跳跃、回退的异常。

原因分析

Plotly绘制折线图时,是按照DataFrame中行的先后顺序连接数据点,而非x轴的分类排列顺序。原始DataFrame中柬埔寨的month_year顺序是乱的,所以折线连接顺序跟着行走,导致异常。

解决方案

方法1:按指定有序列表排序DataFrame

通过将month_year设置为有序类别,再对DataFrame排序,确保数据点按时间顺序排列:

# 给month_year列设置有序类别,指定顺序为ordered_months
df3['month_year'] = pd.Categorical(df3['month_year'], categories=ordered_months, ordered=True)

# 按国家和年月排序,保证每个国家的点按时间顺序排列
df3_sorted = df3.sort_values(by=['country', 'month_year'])

# 使用排序后的DataFrame绘图
fig = px.line(df3_sorted, x="month_year", y="count", color='country', symbol='country')
fig.update_xaxes(categoryarray=ordered_months)
fig.show()

方法2:转换为时间类型(更推荐)

将字符串格式的年月转换为Pandas时间类型,Plotly会自动识别时间顺序,同时方便后续时间相关分析:

# 将month_year转换为时间类型,format参数匹配字符串格式
df3['month_year'] = pd.to_datetime(df3['month_year'], format='%Y-%b')

# 按国家和时间排序
df3_sorted = df3.sort_values(by=['country', 'month_year'])

# 绘图时设置x轴显示为年月格式
fig = px.line(df3_sorted, x="month_year", y="count", color='country', symbol='country')
fig.update_xaxes(tickformat='%Y-%b')
fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:05:40