使用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()

最近更新

  1. TCP协议是安全的吗?

    2024-01-10 00:24:03       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-10 00:24:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-10 00:24:03       20 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-10 00:24:03       20 阅读

热门阅读

  1. 学习今说,与君共勉

    2024-01-10 00:24:03       30 阅读
  2. sqlalchemy expire_all 方法详解,强制刷新会话缓存

    2024-01-10 00:24:03       37 阅读
  3. Qt5.14.2实现将html文件转换为pdf文件

    2024-01-10 00:24:03       27 阅读
  4. Vue的Computed、Methods和Watch

    2024-01-10 00:24:03       48 阅读
  5. 快速排序和冒泡排序

    2024-01-10 00:24:03       39 阅读
  6. linux下数据库定时备份

    2024-01-10 00:24:03       36 阅读
  7. MySQL数据类型

    2024-01-10 00:24:03       45 阅读