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

如何为Pandas DataFrame两类数据绘制带对数y轴的并排累积图

调整后可运行代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import LogFormatterMathtext

# 构造数据集,修正原日期字段未加引号的语法问题
d = {'label': ['true', 'false', 'true', 'false', 'false'],
     'count': [4, 24, 31, 2, 3],
     'date': ['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04', '2019-01-05']}
df = pd.DataFrame(d)
# 转换为标准日期格式,保证x轴显示正常
df['date'] = pd.to_datetime(df['date'])

# 原透视表、累计和计算逻辑完全保留
pivot = pd.pivot_table(df, values="count", index=["date"], columns=["label"], aggfunc=np.sum)
pivot = pivot.cumsum()

# 创建1行2列的并排子图容器
fig, (ax_false, ax_true) = plt.subplots(1, 2, figsize=(20,7))

# 绘制label为false的子图
ax_false.plot(pivot['false'])
ax_false.set_title('Label = false')
ax_false.set_xlabel('Time')
ax_false.set_ylabel('Cumulative number')
# 开启y轴对数刻度
ax_false.set_yscale('log')
# 格式化y轴刻度为10^x的数学格式
ax_false.yaxis.set_major_formatter(LogFormatterMathtext(base=10))

# 绘制label为true的子图
ax_true.plot(pivot['true'])
ax_true.set_title('Label = true')
ax_true.set_xlabel('Time')
ax_true.set_ylabel('Cumulative number')
ax_true.set_yscale('log')
ax_true.yaxis.set_major_formatter(LogFormatterMathtext(base=10))

# 自动调整布局避免标签重叠
plt.tight_layout()
plt.show()

核心调整说明

  • 调用plt.subplots(1, 2)创建1行2列的子图对象,实现两幅折线图并排展示
  • 为每个子图单独调用set_yscale('log')开启对数刻度,匹配y轴刻度要求
  • 导入LogFormatterMathtext格式化y轴刻度,自动渲染为$100$、$101$、$10^2$的标准数学格式
  • 修正了原始数据集日期字段未加引号的语法问题,转换为datetime格式保证x轴显示正常
  • 原有透视表、累计和的计算逻辑完全保留,无需修改原有数据处理流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:15:00