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

创建带两个次Y轴的双轴图表:展示月度用户出行与分类型平均时长

双轴图表实现:月度出行次数与两类用户平均出行时长

步骤1:数据预处理

先清洗并转换原始数据,适配后续分析需求:

  • 修复duration列的格式问题,转换为浮点型
  • 将start_time转为datetime格式并提取月份字段
  • 把user哑变量映射为对应的用户类型
import pandas as pd
import matplotlib.pyplot as plt

# 原始数据
ds = {"duration":['1.02', '1.03', '1.08', '1.07', '2.02', '1,01'], 
      "start_time": ['2019-01-01 00:07:10.576', '2019-01-31 23:48:50.0920', '2019-01-01 00:11:03.441', '2019-01-31 20:58:33.8860', '2019-01-01 00:11:03.441', '2019-01-01 00:14:48.398'],
      "user": [0, 1, 1, 0, 1, 0]
     }
df = pd.DataFrame(ds) 

# 数据清洗与转换
df['duration'] = df['duration'].str.replace(',', '.').astype(float)
df['start_time'] = pd.to_datetime(df['start_time'])
df['month'] = df['start_time'].dt.to_period('M')  # 提取月份维度
df['user_type'] = df['user'].map({0: 'customer', 1: 'subscriber'})

步骤2:数据聚合

按月份分组,计算需要展示的核心指标:

  • 月度总出行次数
  • customer用户的月度平均出行时长
  • subscriber用户的月度平均出行时长
# 聚合月度总出行次数
count_df = df.groupby('month').size().reset_index(name='total_trips')

# 聚合两类用户的平均出行时长
avg_duration_df = df.groupby(['month', 'user_type'])['duration'].mean().unstack()

# 合并指标数据
agg_df = pd.merge(count_df, avg_duration_df, on='month')

步骤3:绘制双轴图表

用Matplotlib构建双轴可视化:

  • 左侧主轴用柱状图展示月度总出行次数
  • 右侧次轴用两条折线分别展示两类用户的平均出行时长
# 创建画布与主轴对象
fig, ax1 = plt.subplots(figsize=(10, 6))

# 主轴:柱状图展示总出行次数
color = '#1f77b4'
ax1.set_xlabel('月份')
ax1.set_ylabel('月度总出行次数', color=color)
bars = ax1.bar(agg_df['month'].astype(str), agg_df['total_trips'], color=color, alpha=0.7)
ax1.tick_params(axis='y', labelcolor=color)

# 给柱状图添加数据标签
for bar in bars:
    height = bar.get_height()
    ax1.text(bar.get_x() + bar.get_width()/2., height,
             f'{int(height)}',
             ha='center', va='bottom')

# 创建右侧次轴
ax2 = ax1.twinx()

# 次轴:折线图展示两类用户平均时长
color2 = '#ff7f0e'
color3 = '#2ca02c'
line1, = ax2.plot(agg_df['month'].astype(str), agg_df['customer'], color=color2, marker='o', label='Customer平均时长')
line2, = ax2.plot(agg_df['month'].astype(str), agg_df['subscriber'], color=color3, marker='s', label='Subscriber平均时长')
ax2.set_ylabel('平均出行时长(单位)', color='black')
ax2.tick_params(axis='y')

# 添加图例
ax2.legend(handles=[line1, line2], loc='upper left')

# 调整布局避免标签重叠
fig.tight_layout()
plt.title('月度出行次数与用户平均出行时长')
plt.show()

补充说明

  • 示例数据仅包含2019年1月的数据,若有多个月份数据,图表会自动展示月度趋势变化
  • 可根据需求自定义颜色、图例位置、图表尺寸等样式参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:20:29