Chart Generator

Polar Sponsor
爱发电 赞助
.NET 9.0

数据可视化图表生成器。适用于为报告、演示或文档根据数据创建图表,支持柱状图、折线图、饼图、散点图等。

图表生成器 : 专业数据可视化图表生成器用于报告、演示文稿和文件

功能概述

图表生成器 : 专业数据可视化图表生成器用于报告、演示文稿和文件是一项面向实际任务的技能,主要用于图片 : 多图类型 : 栏、 线、 派、 散射、 雷达、 区域、 堆叠的。它将相关步骤、工具调用和结果整理方式集中到统一流程中,帮助使用者更快完成目标并减少重复操作。

核心要点

  • 使用时应结合输入条件选择合适的执行方式,核对必要参数、依赖环境与输出内容,并按原始要求处理异常情况。
  • 该技能适合需要稳定复用相关能力的场景,可作为自动化工作流的一部分,也便于后续检查、调整和扩展。
  • 从功能定位来看,该技能强调把分散的操作要求整理成清晰、可复用的处理流程,使用户能够围绕既定目标快速准备输入、选择执行方式并获得结构化结果。

使用与执行

实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。

结果检查与注意事项

执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。

图表生成器

面向报告、演示文稿和文档的专业数据可视化图表生成工具。

功能特性

  • 📊 多种图表类型:柱状图、折线图、饼图、散点图、雷达图、面积图、堆叠图
  • 📁 多种数据源支持:CSV、Excel、JSON、手动输入、网页、文档内容提取
  • 🎨 专业样式配置:简洁、出版级图表,支持高度自定义选项
  • 📐 灵活输出格式:PNG、SVG、PDF、Word、Excel、Markdown、HTML
  • 🔗 嵌入支持:可直接嵌入至各类文档中
  • 🌍 多语言支持:中文、英文、日文、韩文(无编码问题)
  • ✅ 跨平台兼容:Windows、macOS、Linux

支持的图表类型

类型 适用场景 最佳用途
柱状图 数值对比 销售数据、排名展示
折线图 趋势呈现 时间序列、增长分析
饼图 比例构成 市场份额、组成结构
散点图 相关性分析 数据间关系探索
雷达图 多维指标对比 综合性能评估
面积图 累积值展示 堆叠型数据分布
堆叠柱状图 构成分解 多类别细分结构

触发条件

  • “帮我画图” / “Create a chart”
  • “生成柱状图” / “Generate bar chart”
  • “数据可视化” / “Data visualization”
  • “做一个趋势图” / “Make a trend chart”
  • “图表分析” / “Chart analysis”
  • “chart-generator”

步骤 1:明确需求

请提供以下信息:

图表类型:(柱状图/折线图/饼图/散点图/雷达图)
数据来源:(手动输入/CSV/Excel/JSON)
数据内容:
标题:
X轴标签:
Y轴标签:
输出格式:(PNG/SVG)
颜色要求:(默认/自定义)

步骤 2:生成图表

Python 脚本模板

python3 << 'PYEOF'
import os
import matplotlib.pyplot as plt
import matplotlib
import pandas as pd
import numpy as np
from matplotlib import font_manager

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['Noto Sans SC', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

class ChartGenerator:
    def __init__(self):
        self.fig = None
        self.ax = None
        
    def create_bar_chart(self, labels, values, title='',
                         xlabel='', ylabel='',
                         color='#3182ce', output_path=None):
        """Create bar chart"""
        self.fig, self.ax = plt.subplots(figsize=(10, 6))
        
        bars = self.ax.bar(labels, values, color=color, edgecolor='white', linewidth=0.5)
        
        # Add value labels on bars
        for bar in bars:
            height = bar.get_height()
            self.ax.text(bar.get_x() + bar.get_width()/2., height,
                        f'{height:,.0f}',
                        ha='center', va='bottom', fontsize=10)
        
        self.ax.set_title(title, fontsize=16, fontweight='bold', pad=20)
        self.ax.set_xlabel(xlabel, fontsize=12)
        self.ax.set_ylabel(ylabel, fontsize=12)
        
        # Clean styling
        self.ax.spines['top'].set_visible(False)
        self.ax.spines['right'].set_visible(False)
        self.ax.grid(axis='y', alpha=0.3)
        
        plt.tight_layout()
        
        if output_path:
            self.fig.savefig(output_path, dpi=150, bbox_inches='tight')
            plt.close()
            return output_path
        
        return self.fig
    
    def create_line_chart(self, x_data, y_data_list, labels=None,
                         title='', xlabel='', ylabel='',
                         colors=None, output_path=None):
        """Create line chart"""
        self.fig, self.ax = plt.subplots(figsize=(10, 6))
        
        if colors is None:
            colors = ['#3182ce', '#48bb78', '#ed8936', '#e53e3e', '#9f7aea']
        
        for i, y_data in enumerate(y_data_list):
            color = colors[i % len(colors)]
            label = labels[i] if labels and i < len(labels) else f'Series {i+1}'
            self.ax.plot(x_data, y_data, marker='o', linewidth=2, 
                        color=color, label=label, markersize=6)
        
        self.ax.set_title(title, fontsize=16, fontweight='bold', pad=20)
        self.ax.set_xlabel(xlabel, fontsize=12)
        self.ax.set_ylabel(ylabel, fontsize=12)
        
        if labels:
            self.ax.legend(loc='best', framealpha=0.9)
        
        self.ax.spines['top'].set_visible(False)
        self.ax.spines['right'].set_visible(False)
        self.ax.grid(alpha=0.3)
        
        plt.tight_layout()
        
        if output_path:
            self.fig.savefig(output_path, dpi=150, bbox_inches='tight')
            plt.close()
            return output_path
        
        return self.fig
    
    def create_pie_chart(self, labels, values, title='',
                        colors=None, output_path=None):
        """Create pie chart"""
        self.fig, self.ax = plt.subplots(figsize=(8, 8))
        
        if colors is None:
            colors = ['#3182ce', '#48bb78', '#ed8936', '#e53e3e', '#9f7aea',
                     '#38b2ac', '#d69e2e', '#667eea']
        
        wedges, texts, autotexts = self.ax.pie(
            values, labels=labels, colors=colors[:len(values)],
            autopct='%1.1f%%', startangle=90,
            textprops={'fontsize': 11}
        )
        
        for autotext in autotexts:
            autotext.set_color('white')
            autotext.set_fontweight('bold')
        
        self.ax.set_title(title, fontsize=16, fontweight='bold', pad=20)
        
        plt.tight_layout()
        
        if output_path:
            self.fig.savefig(output_path, dpi=150, bbox_inches='tight')
            plt.close()
            return output_path
        
        return self.fig
    
    def create_scatter_plot(self, x_data, y_data, title='',
                           xlabel='', ylabel='',
                           color='#3182ce', output_path=None):
        """Create scatter plot"""
        self.fig, self.ax = plt.subplots(figsize=(10, 6))
        
        self.ax.scatter(x_data, y_data, c=color, alpha=0.6, s=50)
        
        # Add trend line
        z = np.polyfit(x_data, y_data, 1)
        p = np.poly1d(z)
        self.ax.plot(x_data, p(x_data), '--', color='#e53e3e', alpha=0.8, label='Trend')
        
        self.ax.set_title(title, fontsize=16, fontweight='bold', pad=20)
        self.ax.set_xlabel(xlabel, fontsize=12)
        self.ax.set_ylabel(ylabel, fontsize=12)
        self.ax.legend()
        
        self.ax.spines['top'].set_visible(False)
        self.ax.spines['right'].set_visible(False)
        self.ax.grid(alpha=0.3)
        
        plt.tight_layout()
        
        if output_path:
            self.fig.savefig(output_path, dpi=150, bbox_inches='tight')
            plt.close()
            return output_path
        
        return self.fig
    
    def create_multi_bar_chart(self, labels, data_dict, title='',
                              xlabel='', ylabel='', output_path=None):
        """Create grouped bar chart"""
        self.fig, self.ax = plt.subplots(figsize=(12, 6))
        
        x = np.arange(len(labels))
        width = 0.8 / len(data_dict)
        
        colors = ['#3182ce', '#48bb78', '#ed8936', '#e53e3e', '#9f7aea']
        
        for i, (name, values) in enumerate(data_dict.items()):
            offset = (i - len(data_dict)/2 + 0.5) * width
            bars = self.ax.bar(x + offset, values, width, label=name,
                             color=colors[i % len(colors)], edgecolor='white')
        
        self.ax.set_title(title, fontsize=16, fontweight='bold', pad=20)
        self.ax.set_xlabel(xlabel, fontsize=12)
        self.ax.set_ylabel(ylabel, fontsize=12)
        self.ax.set_xticks(x)
        self.ax.set_xticklabels(labels)
        self.ax.legend()
        
        self.ax.spines['top'].set_visible(False)
        self.ax.spines['right'].set_visible(False)
        self.ax.grid(axis='y', alpha=0.3)
        
        plt.tight_layout()
        
        if output_path:
            self.fig.savefig(output_path, dpi=150, bbox_inches='tight')
            plt.close()
            return output_path
        
        return self.fig
    
    def load_from_csv(self, csv_path, x_col=None, y_cols=None):
        """Load data from CSV file"""
        df = pd.read_csv(csv_path)
        
        if x_col is None:
            x_col = df.columns[0]
        if y_cols is None:
            y_cols = [col for col in df.columns if col != x_col]
        
        return {
            'x': df[x_col].tolist(),
            'y': {col: df[col].tolist() for col in y_cols},
            'df': df
        }
    
    def load_from_excel(self, excel_path, sheet_name=0, x_col=None, y_cols=None):
        """Load data from Excel file"""
        df = pd.read_excel(excel_path, sheet_name=sheet_name)
        
        if x_col is None:
            x_col = df.columns[0]
        if y_cols is None:
            y_cols = [col for col in df.columns if col != x_col]
        
        return {
            'x': df[x_col].tolist(),
            'y': {col: df[col].tolist() for col in y_cols},
            'df': df
        }
    
    def load_from_json(self, json_path):
        """Load data from JSON file"""
        import json
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        return data
    
    def load_from_directory(self, dir_path, file_pattern='*.csv'):
        """Load and aggregate data from multiple files in directory"""
        import glob
        
        all_data = []
        for file_path in glob.glob(os.path.join(dir_path, file_pattern)):
            if file_path.endswith('.csv'):
                df = pd.read_csv(file_path)
            elif file_path.endswith('.xlsx'):
                df = pd.read_excel(file_path)
            else:
                continue
            df['source_file'] = os.path.basename(file_path)
            all_data.append(df)
        
        if all_data:
            return pd.concat(all_data, ignore_index=True)
        return pd.DataFrame()
    
    def extract_data_from_text(self, text):
        """Extract numerical data from text content"""
        import re
        
        # Find patterns like "Sales: 100" or "销售额:100万"
        patterns = [
            r'(\w+)\s*[::]\s*(\d+(?:\.\d+)?)',
            r'(\d+(?:\.\d+)?)\s*[::]\s*(\w+)',
        ]
        
        data = {}
        for pattern in patterns:
            matches = re.findall(pattern, text)
            for match in matches:
                if len(match) == 2:
                    key, value = match
                    try:
                        data[key] = float(value)
                    except ValueError:
                        pass
        
        return data
    
    def save_to_png(self, output_path, dpi=150):
        """Save chart as PNG"""
        if self.fig:
            self.fig.savefig(output_path, dpi=dpi, bbox_inches='tight', 
                           facecolor='white', edgecolor='none')
            return output_path
    
    def save_to_svg(self, output_path):
        """Save chart as SVG"""
        if self.fig:
            self.fig.savefig(output_path, format='svg', bbox_inches='tight',
                           facecolor='white', edgecolor='none')
            return output_path
    
    def save_to_pdf(self, output_path):
        """Save chart as PDF"""
        if self.fig:
            self.fig.savefig(output_path, format='pdf', bbox_inches='tight',
                           facecolor='white', edgecolor='none')
            return output_path
    
    def save_to_base64(self, format='png'):
        """Convert chart to base64 string for embedding"""
        import io
        import base64
        
        if self.fig:
            buffer = io.BytesIO()
            self.fig.savefig(buffer, format=format, bbox_inches='tight',
                           facecolor='white', edgecolor='none')
            buffer.seek(0)
            img_str = base64.b64encode(buffer.read()).decode()
            return f'data:image/{format};base64,{img_str}'
    
    def embed_in_markdown(self, title='', caption=''):
        """Generate markdown with embedded chart"""
        base64_img = self.save_to_base64('png')
        
        md = f'\n'
        if title:
            md += f'## {title}\n\n'
        md += f'![{title}]({base64_img})\n'
        if caption:
            md += f'\n*{caption}*\n'
        
        return md
    
    def embed_in_html(self, title='', width='100%'):
        """Generate HTML with embedded chart"""
        base64_img = self.save_to_base64('png')
        
        html = f'''\
{f'

{title}

' if title else ''} {title}
''' return html def save_to_word(self, output_path, title='', caption=''): """Save chart to Word document""" from docx import Document from docx.shared import Inches doc = Document() if title: doc.add_heading(title, level=2) # Save chart as temporary image temp_img = output_path.replace('.docx', '_temp.png') self.save_to_png(temp_img) # Add image to document doc.add_picture(temp_img, width=Inches(6)) if caption: last_para = doc.paragraphs[-1] last_para.alignment = 1 # Center doc.save(output_path) # Clean up temp file if os.path.exists(temp_img): os.remove(temp_img) return output_path # Example usage generator = ChartGenerator() output_dir = os.environ.get('OPENCLAW_WORKSPACE', os.getcwd()) # Bar chart labels = ['Q1', 'Q2', 'Q3', 'Q4'] values = [150000, 180000, 220000, 280000] generator.create_bar_chart( labels, values, title='2026 Quarterly Sales', xlabel='Quarter', ylabel='Sales ($)', output_path=os.path.join(output_dir, 'bar_chart.png') ) # Line chart months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] product_a = [100, 120, 140, 160, 180, 200] product_b = [80, 95, 110, 130, 150, 170] generator.create_line_chart( months, [product_a, product_b], labels=['Product A', 'Product B'], title='Sales Trend', xlabel='Month', ylabel='Sales', output_path=os.path.join(output_dir, 'line_chart.png') ) # Pie chart pie_labels = ['Product A', 'Product B', 'Product C', 'Others'] pie_values = [35, 25, 20, 20] generator.create_pie_chart( pie_labels, pie_values, title='Market Share', output_path=os.path.join(output_dir, 'pie_chart.png') ) print(f"✅ Charts generated in: {output_dir}") PYEOF

数据来源

从 CSV 文件读取

generator = ChartGenerator()
data = generator.load_from_csv('data.csv', x_col='Month', y_cols=['Sales', 'Profit'])

generator.create_line_chart(
    data['x'], 
    [data['y']['Sales'], data['y']['Profit']],
    labels=['Sales', 'Profit'],
    title='Monthly Performance'
)

从 Excel 文件读取

data = generator.load_from_excel('report.xlsx', sheet_name='Sheet1')

手动输入数据

labels = ['A', 'B', 'C', 'D']
values = [100, 200, 150, 300]
generator.create_bar_chart(labels, values)

样式选项

颜色配置

# 单色模式
color='#3182ce'  # 蓝色

# 多色模式
colors=['#3182ce', '#48bb78', '#ed8936', '#e53e3e']

尺寸配置

# 默认尺寸
figsize=(10, 6)

# 演示文稿大尺寸
figsize=(16, 9)

# 报告正方形尺寸
figsize=(8, 8)

安全说明

  • ✅ 不发起任何网络请求或调用外部端点
  • ✅ 无需提供凭证或 API 密钥
  • ✅ 仅在本地处理文件
  • ✅ 使用开源依赖(matplotlib、pandas)
  • ✅ 不向任何外部服务器上传数据

备注说明

  • 基于 matplotlib 实现图表生成
  • 支持 CSV、Excel 及手动输入等多种数据源
  • 输出格式包括:PNG、SVG、PDF
  • 通过 Noto Sans SC 支持中文显示
  • 跨平台兼容(Windows/macOS/Linux)

相关专题

更多
Docker Desktop怎么设置端口映射
Docker Desktop怎么设置端口映射

本专题聚焦Docker Desktop容器端口映射与访问配置,整理从创建容器、设置端口绑定到验证本地服务访问的操作流程。针对端口被占用、映射配置错误、容器服务无法访问等情况,也提供相应的检查方向,方便用户完成端口配置。

2026.11.03

0

18

Docker Desktop镜像构建教程
Docker Desktop镜像构建教程

想使用Docker Desktop将本地项目构建成Docker镜像?本专题围绕镜像构建的实际操作展开,介绍Dockerfile编写、构建命令使用、镜像标签设置和构建日志查看等内容,同时整理镜像无法生成、依赖安装失败及构建缓存异常等问题的排查思路。

2026.11.03

0

11

Docker Desktop容器创建指南
Docker Desktop容器创建指南

本专题聚焦Docker Desktop容器创建与运行配置,介绍通过本地镜像或远程镜像创建容器的方法,以及容器启动、终端访问、日志查看和基础管理等操作。针对端口冲突、参数配置不当、容器无法启动等情况,也整理了相应的排查方向。

2026.11.03

0

11

Tailwind CSS 如何制作导航栏和卡片
Tailwind CSS 如何制作导航栏和卡片

用 Tailwind CSS 制作导航栏和卡片,可先搭建语义化结构,再组合 Flex、Grid、间距、圆角与阴影类。这里整理横向导航、移动端菜单、卡片网格及悬停效果的相关文章,帮助你把常见页面组件做得清晰且适配不同屏幕。

2026.11.03

0

17

Tailwind CSS 响应式布局怎么写
Tailwind CSS 响应式布局怎么写

Tailwind CSS 响应式布局通常从移动端样式写起,再用 sm、md、lg 等前缀调整不同屏幕宽度下的网格、间距和导航。本专题整理断点配置、Grid 与 Flex 自适应布局及常见溢出问题,帮助你逐步完成多设备适配。

2026.11.03

0

19

Tailwind CSS 常用类名怎么记
Tailwind CSS 常用类名怎么记

Tailwind CSS 类名很多,先按布局、间距、文字、颜色和状态分组记忆,再通过官方文档检索具体写法。本专题结合类名排序、动态拼接失效、自定义实用类等问题,帮助你建立常用类名的速查方法。

2026.11.03

0

12

码上飞入口地址合集
码上飞入口地址合集

本专题汇总了码上飞(CodeFlying)的官方入口地址合集,涵盖官网主站及网页版在线使用入口,支持注册登录后直接在线体验零代码AI应用生成。同时整理了APP端下载渠道与小程序入口,助你快速访问平台,通过自然语言描述需求即可生成应用、小程序或网站。

2026.11.03

0

10

Uvicorn 报错与问题解决教程
Uvicorn 报错与问题解决教程

本专题汇总了Uvicorn服务器常见问题与报错解决的教程合集,涵盖启动失败、端口占用、模块导入错误、事件循环冲突及热重载失效等典型故障的排查思路。同时整理了多进程与Worker配置、SSL/HTTPS证书报错、跨域与代理配置等实战解决方案,助你快速定位并解决Uvicorn运行中的各类问题。

2026.11.02

0

14

Uvicorn使用教程
Uvicorn使用教程

本专题汇总了Uvicorn使用教程与启动运行指南,涵盖其作为Python ASGI服务器的定位与特点,以及命令行启动(uvicorn main:app --reload)、参数配置(host/port/workers)、程序内嵌运行与Gunicorn结合部署等核心用法。同时整理了热重载调试、日志配置与生产环境部署优化等技巧,助你快速掌握Uvicorn的运行与配置。

2026.11.02

0

17

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
热门推荐
/
最新课程
phpStudy极速入门视频教程
phpStudy极速入门视频教程

共6课时 | 54.7万人学习

独孤九贱(4)_PHP视频教程
独孤九贱(4)_PHP视频教程

共89课时 | 134.1万人学习