1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
| import matplotlib.pyplot as plt import pandas as pd import numpy as np from datetime import datetime
class FinanceVisualizer: """财务数据可视化工具""" def __init__(self): plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False self.data = None def load_data(self, filepath): """加载CSV数据""" try: self.data = pd.read_csv(filepath) print(f"✅ 加载成功: {len(self.data)}行数据") return True except Exception as e: print(f"❌ 加载失败: {e}") return False def create_bar_chart(self, x_col, y_col, title="柱状图"): """通用柱状图""" if self.data is None: print("⚠️ 请先加载数据") return plt.figure(figsize=(10, 6)) if self.data[x_col].dtype == 'object': plt.bar(self.data[x_col], self.data[y_col], color='#4CAF50', alpha=0.8) else: plt.scatter(self.data[x_col], self.data[y_col], s=100, color='#FF5722') plt.title(title, fontsize=14, fontweight='bold') plt.xlabel(x_col) plt.ylabel(y_col) plt.grid(axis='y', linestyle='--', alpha=0.7) plt.xticks(rotation=45) plt.tight_layout() filename = f"{title}_{datetime.now().strftime('%Y%m%d')}.png" plt.savefig(filename, dpi=150) print(f"✅ 已保存: {filename}") plt.show() def create_line_chart(self, x_col, y_cols, title="折线图"): """多系列折线图""" if self.data is None: print("⚠️ 请先加载数据") return plt.figure(figsize=(12, 6)) if isinstance(y_cols, str): y_cols = [y_cols] colors = plt.cm.tab10(np.linspace(0, 1, len(y_cols))) for i, y_col in enumerate(y_cols): plt.plot(self.data[x_col], self.data[y_col], marker='o', label=y_col, color=colors[i], linewidth=2) plt.title(title, fontsize=14, fontweight='bold') plt.xlabel(x_col) plt.ylabel('数值') plt.legend() plt.grid(True, linestyle='--', alpha=0.6) plt.xticks(rotation=45) plt.tight_layout() filename = f"{title}_{datetime.now().strftime('%Y%m%d')}.png" plt.savefig(filename, dpi=150) print(f"✅ 已保存: {filename}") plt.show() def create_pie_chart(self, labels_col, values_col, title="饼图"): """饼图""" if self.data is None: print("⚠️ 请先加载数据") return plt.figure(figsize=(10, 8)) if self.data[values_col].sum() <= 0: print("⚠️ 数据无效,无法绘制饼图") return colors = plt.cm.Set3(np.linspace(0, 1, len(self.data))) wedges, texts, autotexts = plt.pie( self.data[values_col], labels=self.data[labels_col], autopct='%1.1f%%', colors=colors, startangle=140, textprops={'fontsize': 10} ) for autotext in autotexts: autotext.set_color('white') autotext.set_fontweight('bold') plt.title(title, fontsize=14, fontweight='bold') plt.axis('equal') plt.tight_layout() filename = f"{title}_{datetime.now().strftime('%Y%m%d')}.png" plt.savefig(filename, dpi=150) print(f"✅ 已保存: {filename}") plt.show() def create_report(self, charts_config, title="数据报告"): """生成多图表报告""" n = len(charts_config) cols = 2 rows = (n + 1) // 2 fig, axes = plt.subplots(rows, cols, figsize=(15, rows*5)) if rows == 1: axes = axes.reshape(1, -1) axes = axes.flatten() for i, config in enumerate(charts_config): ax = axes[i] if config['type'] == 'bar': ax.bar(self.data[config['x']], self.data[config['y']], color=config.get('color', '#4CAF50')) ax.set_title(config.get('title', ''), fontweight='bold') ax.set_ylabel(config['y']) ax.grid(axis='y', linestyle='--', alpha=0.7) elif config['type'] == 'line': for y_col in config['y']: ax.plot(self.data[config['x']], self.data[y_col], marker='o', label=y_col) ax.set_title(config.get('title', ''), fontweight='bold') ax.legend() ax.grid(True, linestyle='--', alpha=0.6) elif config['type'] == 'pie': ax.pie(self.data[config['y']], labels=self.data[config['x']], autopct='%1.1f%%') ax.set_title(config.get('title', ''), fontweight='bold') ax.axis('equal') else: ax.text(0.5, 0.5, '未知图表类型', ha='center', va='center') ax.set_xlabel(config['x']) for i in range(len(charts_config), len(axes)): axes[i].set_visible(False) fig.suptitle(title, fontsize=16, fontweight='bold', y=0.98) plt.tight_layout(rect=[0, 0, 1, 0.96]) filename = f"{title}_{datetime.now().strftime('%Y%m%d')}.png" plt.savefig(filename, dpi=300) print(f"✅ 报告已保存: {filename} (高清)") plt.show()
def main(): """主菜单""" visualizer = FinanceVisualizer() while True: print("\n" + "=" * 50) print("财务数据可视化工具") print("=" * 50) print("1. 加载CSV数据") print("2. 创建柱状图") print("3. 创建折线图") print("4. 创建饼图") print("5. 生成综合报告") print("6. 退出") print("=" * 50) choice = input("请选择: ").strip() if choice == "1": filepath = input("CSV文件路径: ").strip() visualizer.load_data(filepath) elif choice == "2": if visualizer.data is not None: x = input("X轴列名: ").strip() y = input("Y轴列名: ").strip() title = input("图表标题: ").strip() or "柱状图" visualizer.create_bar_chart(x, y, title) else: print("⚠️ 请先加载数据") elif choice == "3": if visualizer.data is not None: x = input("X轴列名: ").strip() y = input("Y轴列名(多个用逗号分隔): ").strip().split(',') title = input("图表标题: ").strip() or "折线图" visualizer.create_line_chart(x, y, title) else: print("⚠️ 请先加载数据") elif choice == "4": if visualizer.data is not None: labels = input("标签列名: ").strip() values = input("数值列名: ").strip() title = input("图表标题: ").strip() or "饼图" visualizer.create_pie_chart(labels, values, title) else: print("⚠️ 请先加载数据") elif choice == "5": if visualizer.data is not None: print("\n请配置报告(输入图表数量):") n = int(input("图表数量: ").strip()) configs = [] for i in range(n): print(f"\n图表 {i+1} 配置:") t = input(" 类型(bar/line/pie): ").strip() x = input(" X轴列名: ").strip() y = input(" Y轴列名: ").strip() title = input(" 图表标题: ").strip() configs.append({ 'type': t, 'x': x, 'y': y if t == 'pie' else [y], 'title': title }) title = input("总标题: ").strip() or "数据报告" visualizer.create_report(configs, title) else: print("⚠️ 请先加载数据") elif choice == "6": print("👋 再见!") break else: print("请输入1-6!")
if __name__ == "__main__": main()
|