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

用R绘制多费用类别年度求和的时间序列图

没问题,我来帮你搞定这个时间序列图的制作!你的需求很明确——按年度汇总四类费用的总额(自动剔除NA值),然后画出分品类的折线图。下面是具体的步骤和代码示例,用Python的pandas和可视化库来实现,处理5万行数据完全不在话下:

第一步:数据预处理(用Pandas)

首先我们需要用Pandas读取数据,并按年度对每类费用求和,Pandas的sum()方法默认会忽略NA值,刚好符合你的需求:

import pandas as pd

# 读取数据,根据你的实际文件格式调整(比如Excel用pd.read_excel)
df = pd.read_csv('your_expense_data.csv')

# 按Year分组,对所有expense列求和,自动跳过NA值
yearly_expense_totals = df.groupby('Year')[['expense_1', 'expense_2', 'expense_3', 'expense_4']].sum()

# 可以查看处理后的结果,确认是否符合预期
print(yearly_expense_totals)

小提示:如果某些年份某类费用全是NA,默认sum()会返回0;如果想让这类情况保留NA,可以改成sum(min_count=1),这样全NA的年份对应费用会显示为NA,绘图时会自动跳过这些点。

第二步:绘制时间序列折线图

这里提供两种常用的绘图方式,你可以选自己熟悉的:

方式一:用Matplotlib直接绘制

适合需要精细控制图形细节的场景:

import matplotlib.pyplot as plt

# 设置画布大小
plt.figure(figsize=(10, 6))

# 为每类费用绘制折线,添加标记点方便查看数值
plt.plot(yearly_expense_totals.index, yearly_expense_totals['expense_1'], label='Expense 1', marker='o', linewidth=2)
plt.plot(yearly_expense_totals.index, yearly_expense_totals['expense_2'], label='Expense 2', marker='s', linewidth=2)
plt.plot(yearly_expense_totals.index, yearly_expense_totals['expense_3'], label='Expense 3', marker='^', linewidth=2)
plt.plot(yearly_expense_totals.index, yearly_expense_totals['expense_4'], label='Expense 4', marker='d', linewidth=2)

# 添加图表元素,让图形更清晰
plt.xlabel('Year', fontsize=12)
plt.ylabel('Total Expense', fontsize=12)
plt.title('Yearly Total Expenses by Category', fontsize=14, pad=20)
plt.legend(fontsize=10)
plt.grid(alpha=0.3, linestyle='--')

# 显示图形
plt.show()

方式二:用Seaborn绘制(更简洁美观)

Seaborn适合快速生成风格统一的可视化,需要先把数据转成长格式:

import seaborn as sns

# 将宽格式数据转成长格式,适配Seaborn的API
long_format_df = yearly_expense_totals.reset_index().melt(
    id_vars='Year',
    var_name='Expense Category',
    value_name='Total Expense'
)

# 绘制折线图
plt.figure(figsize=(10, 6))
sns.lineplot(
    data=long_format_df,
    x='Year',
    y='Total Expense',
    hue='Expense Category',
    marker='o',
    linewidth=2
)

# 添加图表元素
plt.xlabel('Year', fontsize=12)
plt.ylabel('Total Expense', fontsize=12)
plt.title('Yearly Total Expenses by Category', fontsize=14, pad=20)
plt.grid(alpha=0.3, linestyle='--')
plt.show()

这样就能得到你想要的分品类年度费用时间序列图啦!如果需要调整颜色、标记样式或者其他细节,直接修改代码里的参数就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:20:05