使用python生成一个月度账单消费金额柱状图表

  1. 阿里云月度账单
  2. 根据月份、消费金额(可开票)生成一个柱状图表
import pandas as pd
import matplotlib.pyplot as plt
import os

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用于显示中文的宋体

# 获取当前工作目录下所有CSV文件
csv_files = [file for file in os.listdir() if file.endswith('.csv')]

# 创建一个图表
fig, ax = plt.subplots(figsize=(12, 6))

# 设置柱子的宽度
bar_width = 0.2

# 遍历每个CSV文件
for idx, file in enumerate(csv_files):
    # 读取CSV文件
    df = pd.read_csv(file)

    # 将“账期”列转换为日期格式
    df['账期'] = pd.to_datetime(df['账期'].str.strip(), format='%Y-%m')

    # 过滤掉金额为0的数据
    df = df[df['消费(可开票)'] != 0]

    if not df.empty:
        # 将NaN值替换为0
        df['消费(可开票)'] = df['消费(可开票)'].fillna(0)

        # 获取表格名称
        table_name = file[:-4]

        # 计算柱子的位置,错开显示
        x_positions = [i + idx * bar_width for i in range(len(df))]

        # 绘制柱状图
        bars = ax.bar(x_positions, df['消费(可开票)'], width=bar_width, label=table_name, alpha=0.7)

        # 在每个柱子上添加文本标签,倾斜45度显示
        for bar in bars:
            height = bar.get_height()
            ax.annotate(f'{height:.2f}', xy=(bar.get_x() + bar.get_width() / 2, height),
                        textcoords="offset points", xytext=(0, 5), ha='center', va='bottom', rotation=75)

# 设置图表标题和标签
ax.set_title('年度账单消费情况(阿里云)')
ax.set_xlabel('月份')
ax.set_ylabel('消费金额(可开票)')

# 使用自定义 x 轴标签
ax.set_xticks([i + (len(csv_files) - 1) * bar_width / 2 for i in range(len(df))])
ax.set_xticklabels(df['账期'].dt.strftime('%Y-%m'))


# 添加图例
ax.legend()

# 保存图表到本地
plt.savefig('bar_chart.png')
# 显示图表
plt.show()

你可能感兴趣的:(python)