299 lines
12 KiB
Python
299 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
高级图表生成工具 - 支持更多图表类型
|
|
Advanced chart generation for financing plan
|
|
"""
|
|
|
|
import matplotlib.pyplot as plt
|
|
import matplotlib.patches as mpatches
|
|
import numpy as np
|
|
import pandas as pd
|
|
from matplotlib.sankey import Sankey
|
|
import networkx as nx
|
|
from matplotlib.patches import FancyBboxPatch
|
|
import seaborn as sns
|
|
import os
|
|
import sys
|
|
|
|
# 设置中文字体
|
|
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
|
|
plt.rcParams['axes.unicode_minus'] = False
|
|
|
|
class AdvancedChartGenerator:
|
|
"""高级图表生成器"""
|
|
|
|
def __init__(self, output_dir='charts'):
|
|
self.output_dir = output_dir
|
|
try:
|
|
if not os.path.exists(output_dir):
|
|
os.makedirs(output_dir)
|
|
except Exception as e:
|
|
print(f"创建输出目录失败: {e}")
|
|
sys.exit(1)
|
|
|
|
# 专业配色方案
|
|
self.colors = {
|
|
'primary': '#1F497D',
|
|
'secondary': '#365F91',
|
|
'accent': '#4F81BD',
|
|
'success': '#70AD47',
|
|
'warning': '#FFC000',
|
|
'danger': '#C5504B',
|
|
'info': '#5B9BD5',
|
|
'light': '#F2F2F2',
|
|
'dark': '#404040'
|
|
}
|
|
|
|
def generate_business_canvas_visual(self):
|
|
"""生成可视化商业画布"""
|
|
try:
|
|
fig, ax = plt.subplots(figsize=(16, 12))
|
|
|
|
# 九宫格布局
|
|
canvas_layout = {
|
|
'key_partners': {'pos': (0, 2), 'size': (1, 1), 'title': '关键合作伙伴'},
|
|
'key_activities': {'pos': (1, 2), 'size': (1, 1), 'title': '关键活动'},
|
|
'value_propositions': {'pos': (2, 2), 'size': (1, 1), 'title': '价值主张'},
|
|
'customer_relationships': {'pos': (3, 2), 'size': (1, 1), 'title': '客户关系'},
|
|
'customer_segments': {'pos': (4, 2), 'size': (1, 1), 'title': '客户细分'},
|
|
'key_resources': {'pos': (1, 1), 'size': (1, 1), 'title': '关键资源'},
|
|
'channels': {'pos': (3, 1), 'size': (1, 1), 'title': '渠道通路'},
|
|
'cost_structure': {'pos': (0, 0), 'size': (2, 1), 'title': '成本结构'},
|
|
'revenue_streams': {'pos': (2, 0), 'size': (3, 1), 'title': '收入来源'}
|
|
}
|
|
|
|
colors = [self.colors['primary'], self.colors['secondary'], self.colors['accent'],
|
|
self.colors['success'], self.colors['warning'], self.colors['info'],
|
|
self.colors['danger'], self.colors['dark'], self.colors['primary']]
|
|
|
|
# 绘制画布区块
|
|
for i, (key, layout) in enumerate(canvas_layout.items()):
|
|
x, y = layout['pos']
|
|
w, h = layout['size']
|
|
|
|
# 绘制区块
|
|
rect = FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.02",
|
|
facecolor=colors[i % len(colors)], alpha=0.3,
|
|
edgecolor=colors[i % len(colors)], linewidth=2)
|
|
ax.add_patch(rect)
|
|
|
|
# 添加标题
|
|
ax.text(x + w/2, y + h - 0.1, layout['title'],
|
|
ha='center', va='top', fontsize=12, fontweight='bold',
|
|
color=colors[i % len(colors)])
|
|
|
|
ax.set_xlim(-0.1, 5.1)
|
|
ax.set_ylim(-0.1, 3.1)
|
|
ax.set_aspect('equal')
|
|
ax.axis('off')
|
|
ax.set_title('全生命周期AI监测项目商业画布', fontsize=20, fontweight='bold', pad=30)
|
|
|
|
plt.tight_layout()
|
|
plt.savefig(f'{self.output_dir}/business_canvas_visual.png', dpi=300, bbox_inches='tight')
|
|
plt.close()
|
|
|
|
except Exception as e:
|
|
print(f"生成商业画布图表失败: {e}")
|
|
return False
|
|
return True
|
|
|
|
def generate_gantt_chart(self):
|
|
"""生成项目时间线甘特图"""
|
|
try:
|
|
fig, ax = plt.subplots(figsize=(14, 8))
|
|
|
|
# 项目任务数据
|
|
tasks = [
|
|
{'name': '硬件开发完善', 'start': 0, 'duration': 3, 'color': self.colors['primary']},
|
|
{'name': '软件平台完善', 'start': 1, 'duration': 4, 'color': self.colors['secondary']},
|
|
{'name': '批量生产启动', 'start': 3, 'duration': 2, 'color': self.colors['accent']},
|
|
{'name': '数据中心建设', 'start': 0, 'duration': 6, 'color': self.colors['success']},
|
|
{'name': '市场拓展', 'start': 4, 'duration': 8, 'color': self.colors['warning']},
|
|
{'name': '试点项目部署', 'start': 6, 'duration': 6, 'color': self.colors['info']},
|
|
{'name': '全国推广', 'start': 12, 'duration': 12, 'color': self.colors['danger']},
|
|
]
|
|
|
|
# 绘制甘特图
|
|
for i, task in enumerate(tasks):
|
|
ax.barh(i, task['duration'], left=task['start'],
|
|
color=task['color'], alpha=0.7, height=0.6)
|
|
ax.text(task['start'] + task['duration']/2, i, task['name'],
|
|
ha='center', va='center', fontweight='bold', color='white')
|
|
|
|
ax.set_yticks(range(len(tasks)))
|
|
ax.set_yticklabels([task['name'] for task in tasks])
|
|
ax.set_xlabel('时间线(月)')
|
|
ax.set_title('项目实施时间线', fontsize=16, fontweight='bold')
|
|
ax.grid(True, alpha=0.3)
|
|
|
|
plt.tight_layout()
|
|
plt.savefig(f'{self.output_dir}/project_timeline.png', dpi=300, bbox_inches='tight')
|
|
plt.close()
|
|
|
|
except Exception as e:
|
|
print(f"生成甘特图失败: {e}")
|
|
return False
|
|
return True
|
|
|
|
def generate_risk_assessment_radar(self):
|
|
"""生成风险评估雷达图"""
|
|
try:
|
|
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw=dict(projection='polar'))
|
|
|
|
# 风险维度
|
|
risk_categories = ['技术风险', '市场风险', '运营风险', '财务风险', '政策风险', '竞争风险']
|
|
risk_levels = [3, 2, 3, 2, 1, 2] # 1-5 评分,数值越高风险越大
|
|
|
|
# 计算角度
|
|
angles = np.linspace(0, 2 * np.pi, len(risk_categories), endpoint=False).tolist()
|
|
risk_levels += risk_levels[:1] # 闭合图形
|
|
angles += angles[:1]
|
|
|
|
# 绘制雷达图
|
|
ax.plot(angles, risk_levels, 'o-', linewidth=2, color=self.colors['danger'])
|
|
ax.fill(angles, risk_levels, alpha=0.25, color=self.colors['danger'])
|
|
|
|
# 设置标签
|
|
ax.set_xticks(angles[:-1])
|
|
ax.set_xticklabels(risk_categories)
|
|
ax.set_ylim(0, 5)
|
|
ax.set_title('项目风险评估雷达图', fontsize=16, fontweight='bold', pad=20)
|
|
|
|
# 添加风险等级说明
|
|
ax.text(0.02, 0.98, '风险等级:\n1-低风险\n2-较低风险\n3-中等风险\n4-较高风险\n5-高风险',
|
|
transform=ax.transAxes, verticalalignment='top',
|
|
bbox=dict(boxstyle='round', facecolor='white', alpha=0.8))
|
|
|
|
plt.tight_layout()
|
|
plt.savefig(f'{self.output_dir}/risk_assessment_radar.png', dpi=300, bbox_inches='tight')
|
|
plt.close()
|
|
|
|
except Exception as e:
|
|
print(f"生成风险雷达图失败: {e}")
|
|
return False
|
|
return True
|
|
|
|
def generate_swot_analysis(self):
|
|
"""生成SWOT分析图"""
|
|
try:
|
|
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(14, 10))
|
|
|
|
# SWOT数据
|
|
swot_data = {
|
|
'Strengths': ['技术领先', 'AI算法', '硬件优势', '政府关系', '团队经验'],
|
|
'Weaknesses': ['资金需求大', '市场认知度低', '产品待完善'],
|
|
'Opportunities': ['市场空白', '政策支持', '老龄化趋势', '数字化转型'],
|
|
'Threats': ['竞争对手', '技术变化', '政策变动', '资金风险']
|
|
}
|
|
|
|
colors = [self.colors['success'], self.colors['warning'],
|
|
self.colors['info'], self.colors['danger']]
|
|
axes = [ax1, ax2, ax3, ax4]
|
|
titles = ['优势 (Strengths)', '劣势 (Weaknesses)',
|
|
'机会 (Opportunities)', '威胁 (Threats)']
|
|
|
|
for ax, (key, items), color, title in zip(axes, swot_data.items(), colors, titles):
|
|
y_pos = np.arange(len(items))
|
|
ax.barh(y_pos, [1]*len(items), color=color, alpha=0.7)
|
|
|
|
for i, item in enumerate(items):
|
|
ax.text(0.5, i, item, ha='center', va='center',
|
|
fontweight='bold', color='white')
|
|
|
|
ax.set_yticks([])
|
|
ax.set_xlim(0, 1)
|
|
ax.set_title(title, fontsize=14, fontweight='bold')
|
|
ax.axis('off')
|
|
|
|
fig.suptitle('SWOT分析矩阵', fontsize=18, fontweight='bold')
|
|
plt.tight_layout()
|
|
plt.savefig(f'{self.output_dir}/swot_analysis.png', dpi=300, bbox_inches='tight')
|
|
plt.close()
|
|
|
|
except Exception as e:
|
|
print(f"生成SWOT分析图失败: {e}")
|
|
return False
|
|
return True
|
|
|
|
def generate_all_advanced_charts(self):
|
|
"""生成所有高级图表"""
|
|
print("正在生成高级图表...")
|
|
|
|
results = []
|
|
try:
|
|
print("1. 生成可视化商业画布...")
|
|
results.append(self.generate_business_canvas_visual())
|
|
|
|
print("2. 生成项目时间线甘特图...")
|
|
results.append(self.generate_gantt_chart())
|
|
|
|
print("3. 生成风险评估雷达图...")
|
|
results.append(self.generate_risk_assessment_radar())
|
|
|
|
print("4. 生成SWOT分析图...")
|
|
results.append(self.generate_swot_analysis())
|
|
|
|
if all(results):
|
|
print("✅ 所有高级图表生成完成!")
|
|
return True
|
|
else:
|
|
print("⚠️ 部分图表生成失败")
|
|
return False
|
|
|
|
except Exception as e:
|
|
print(f"❌ 高级图表生成失败: {e}")
|
|
return False
|
|
|
|
def check_dependencies():
|
|
"""检查依赖模块"""
|
|
required_modules = ['matplotlib', 'numpy', 'pandas', 'seaborn']
|
|
missing_modules = []
|
|
|
|
for module in required_modules:
|
|
try:
|
|
__import__(module)
|
|
except ImportError:
|
|
missing_modules.append(module)
|
|
|
|
if missing_modules:
|
|
print(f"❌ 缺少以下模块: {', '.join(missing_modules)}")
|
|
print("请运行: pip install matplotlib numpy pandas seaborn")
|
|
return False
|
|
|
|
return True
|
|
|
|
def main():
|
|
"""主函数"""
|
|
# 检查依赖
|
|
if not check_dependencies():
|
|
return 1
|
|
|
|
try:
|
|
# 生成基础图表(如果存在)
|
|
try:
|
|
from generate_charts import FinancingChartGenerator
|
|
basic_generator = FinancingChartGenerator()
|
|
basic_generator.generate_all_charts()
|
|
except ImportError:
|
|
print("⚠️ 基础图表生成器未找到,仅生成高级图表")
|
|
|
|
# 生成高级图表
|
|
advanced_generator = AdvancedChartGenerator()
|
|
success = advanced_generator.generate_all_advanced_charts()
|
|
|
|
if success:
|
|
print("\n📊 图表生成完成!")
|
|
print(f"📁 保存位置: {advanced_generator.output_dir}/")
|
|
return 0
|
|
else:
|
|
print("\n❌ 图表生成过程中出现错误")
|
|
return 1
|
|
|
|
except Exception as e:
|
|
print(f"❌ 程序执行失败: {e}")
|
|
return 1
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|