Python 财务数据可视化实战 · 模板合集(5 类图表可运行代码)
《Python财务数据可视化实战》系列 5 篇收官。这里把全部代码打包成一个可运行脚本,覆盖月报和经营分析最常用的 5 类图表:营收趋势、产品对比、费用结构、营收利润背离、科目季节性。复制保存为 viz_toolkit.py,改数据即可出图。 ## 完整代码 ```javascript # Finance Visualization Toolkit # Deps: pip install matplotlib numpy import matplotlib.pyplot as plt import numpy as np def chart_revenue_trend(months, revenue, window=3): def moving_avg(data, w): out = [] for i in range(len(data)): s = max(0, i - w + 1) seg = data[s:i + 1] out.append(round(sum(seg) / len(seg), 2)) return out ma = moving_avg(revenue, window) plt.figure(figsize=(8, 4)) plt.plot(months, revenue, marker="o", label="Revenue") plt.plot(months, ma, linestyle="--", label="MA" + str(window)) plt.title("Monthly Revenue Trend") plt.xlabel("Month") plt.ylabel("Revenue (1000 CNY)") plt.legend() plt.grid(True) plt.tight_layout() plt.show() def chart_product_bar(products, rev_this, rev_last): x = range(len(products)) plt.figure(figsize=(8, 4)) plt.bar(x, rev_this, color="steelblue") plt.xticks(x, products) for i, (cur, lst) in enumerate(zip(rev_this, rev_last)): growth = (cur / lst - 1) * 100 plt.text(i, cur + 5, f"+{growth:.1f}%", ha="center") plt.title("Product Revenue vs Last Year") plt.ylabel("Revenue (1000 CNY)") plt.tight_layout() plt.show() def chart_expense_donut(labels, sizes, colors): fig, ax = plt.subplots(figsize=(6, 6)) ax.pie(sizes, labels=labels, colors=colors, autopct="%.1f%%", startangle=90, wedgeprops=dict(width=0.4)) total = sum(sizes) ax.text(0, 0, f"Total\n{total}", ha="center", va="center") plt.title("Expense Structure") plt.tight_layout() plt.show() def chart_revenue_margin_dual(months, revenue, margin): fig, ax1 = plt.subplots(figsize=(8, 4)) ax1.bar(months, revenue, color="steelblue", alpha=0.6) ax1.set_ylabel("Revenue (1000 CNY)") ax2 = ax1.twinx() ax2.plot(months, margin, color="red", marker="o") ax2.set_ylabel("Margin (%)") plt.title("Revenue vs Margin") plt.tight_layout() plt.show() def chart_account_heatmap(accounts, months, data): mat = np.array(data) fig, ax = plt.subplots(figsize=(8, 4)) im = ax.imshow(mat, cmap="YlOrRd", aspect="auto") ax.set_xticks(range(len(months))) ax.set_xticklabels(months) ax.set_yticks(range(len(accounts))) ax.set_yticklabels(accounts) fig.colorbar(im) plt.title("Account Monthly Heatmap") plt.tight_layout() plt.show() if __name__ == "__main__": months8 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug"] revenue8 = [120, 135, 128, 150, 162, 175, 168, 190] chart_revenue_trend(months8, revenue8) products = ["A", "B", "C", "D"] rev_this = [500, 320, 280, 150] rev_last = [420, 300, 310, 120] chart_product_bar(products, rev_this, rev_last) labels = ["Selling", "Admin", "Finance", "R&D"] sizes = [400, 300, 120, 180] colors = ["#4C72B0", "#DD8452", "#55A868", "#C44E52"] chart_expense_donut(labels, sizes, colors) months5 = ["Jan", "Feb", "Mar", "Apr", "May"] revenue5 = [100, 110, 105, 130, 140] margin = [12.0, 11.5, 9.8, 10.2, 8.5] chart_revenue_margin_dual(months5, revenue5, margin) accounts = ["Revenue", "COGS", "Salary", "Travel"] months6 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] matrix = [ [120, 110, 130, 125, 140, 150], [80, 75, 90, 85, 95, 100], [30, 30, 30, 30, 30, 30], [5, 8, 4, 20, 6, 9], ] chart_account_heatmap(accounts, months6, matrix) ``` ## 怎么用 - 安装依赖:`pip install matplotlib numpy`。 - 把 `if __name__ == "__main__"` 里的示例数据换成你的 Excel 数据(用 `pd.read_excel` 读两列再传参)。 - 5 个函数相互独立,想出哪张图调哪个,不想出的注释掉即可。 - 保存图片用 `plt.savefig("图名.png")`,批量出图给月报配图。 ## 小结 这 5 类图表覆盖经营分析 80% 的配图场景。整套代码不到 90 行,复制即用,财务报告的配图以后不用再求人。 --- 觉得这套工具箱省了你翻图表的功夫,点赞收藏 + 关注。关注后翻我主页,前面还有 62 篇《Python审计自动化实战》测算脚本,从勾对、底稿到勾稽全覆盖,照着抄就能搭出自己的审计提效工作流。会计师事务所的一名注册会计师