SuperAPI AI Directory

figures-python

Coding & development

View repository

Updated 10-16 02:32

About this skill

Python Data Charts

This skill guides the use of Python to generate data charts at the level of scientific research papers.

Checklist

  • Confirm that the conda environment is activated (research)
  • Confirm the chart type and data
  • Record the data manifest
  • If mock/synthetic data is used, clearly label it as planning data
  • Use top-journal color schemes
  • Set the resolution to 450 DPI
  • Output both PNG and SVG
  • Check Chinese font display
  • Save to the figures/ directory

1. Environment Requirements

1.1 conda Environment

Default environment name:research

Activation command:

conda activate research

Required libraries:

pip install matplotlib seaborn numpy pandas

If the environment is not configured, call the environment-setup skill.

2. Chart Specifications

2.0 Data Manifest and Mock Data Boundaries

Any data chart must first have a data file and a data manifest. Default path:

figures/data-manifest.md
figures/data/<figure-name>.csv
figures/<section>/<figure-name>.py
figures/<section>/<figure-name>.png
figures/<section>/<figure-name>.svg

figures/data-manifest.md At minimum, record:

Figure Data file Real/mock Source Script Outputs

Mock or synthetic data may only be used for planning-version charts. The file name must start with mock_ or synthetic_ , and [待真实实验替换]must be retained in the chart, table, or section draft. Mock data must not be written as "experimental results show".

2.1 Resolution Requirements

Purpose DPI Description
Journal submission 300-600 Required by most journals
Top-journal submission 450+ Nature/Science, etc.
Screen display 150 PPT/web pages

This skill uses 450 DPI by default

2.2 Output Formats

Each chart outputs two formats at the same time:

  • PNG: bitmap, suitable for web pages and PPT
  • SVG: vector graphic, suitable for journal submission

2.3 Chart Dimensions

Type Width (inches) Applicable scenario
Single-column figure 3.5 Journal single column
Double-column figure 7.0 Journal double column/full width
PPT figure 10.0 Presentation slides

3. Top-Journal Color Schemes

3.1 Nature/Science Style

NATURE_COLORS = ['#2E86AB', '#A23B72', '#F18F01', '#C73E1D', '#95C623']

3.2 Cell Style

CELL_COLORS = ['#4E79A7', '#F28E2B', '#E15759', '#76B7B2', '#59A14F', '#EDC948']

3.3 Colorblind-Friendly Color Scheme

COLORBLIND_SAFE = ['#0077BB', '#33BBEE', '#009988', '#EE7733', '#CC3311', '#EE3377']

3.4 Color Scheme Principles

  • ❌ Do not use matplotlib default colors
  • ❌ Do not use basic colors such as pure red, pure blue, or pure green
  • ✅ Keep the number of colors in the same chart to no more than 5
  • ✅ Ensure colorblind friendliness

4. Code Template

"""
Figure X: [图表标题]
论文章节: [所属章节]
"""

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from pathlib import Path

# 中文字体配置
CHINESE_FONT = None
font_candidates = [
    '/System/Library/Fonts/STHeiti Light.ttc',
    '/System/Library/Fonts/PingFang.ttc',
]
for fp in font_candidates:
    if Path(fp).exists():
        CHINESE_FONT = fm.FontProperties(fname=fp)
        break

plt.rcParams['axes.unicode_minus'] = False

# 顶刊配色
COLORS = ['#4E79A7', '#F28E2B', '#E15759', '#76B7B2', '#59A14F']

def setup_plot_style():
    plt.rcParams.update({
        'font.size': 10,
        'axes.titlesize': 12,
        'axes.labelsize': 10,
        'axes.spines.top': False,
        'axes.spines.right': False,
        'axes.grid': True,
        'grid.alpha': 0.3,
        'legend.frameon': False,
        'savefig.dpi': 450,
        'savefig.bbox': 'tight',
    })

def main():
    setup_plot_style()
    
    fig, ax = plt.subplots(figsize=(7, 5))
    
    # === 绑定代码 ===
    x = np.linspace(0, 10, 100)
    ax.plot(x, np.sin(x), color=COLORS[0], label='Model A')
    ax.plot(x, np.cos(x), color=COLORS[1], label='Model B')
    
    if CHINESE_FONT:
        ax.set_xlabel('时间 (s)', fontproperties=CHINESE_FONT)
        ax.set_ylabel('幅值', fontproperties=CHINESE_FONT)
    else:
        ax.set_xlabel('Time (s)')
        ax.set_ylabel('Amplitude')
    
    ax.legend()
    # === 绑定代码结束 ===
    
    # 保存
    output_dir = Path(__file__).parent
    fig_name = Path(__file__).stem
    plt.savefig(output_dir / f'{fig_name}.png', dpi=450)
    plt.savefig(output_dir / f'{fig_name}.svg')
    plt.show()

if __name__ == '__main__':
    main()

5. Common Chart Types

Line chart

ax.plot(x, y, color=COLORS[0], linewidth=1.5, marker='o', markersize=4)

Bar chart

ax.bar(x_pos, values, color=COLORS[:len(values)], edgecolor='white')

Heatmap

im = ax.imshow(matrix, cmap='RdBu_r', aspect='auto')
plt.colorbar(im, ax=ax)

Box plot

bp = ax.boxplot(data_list, patch_artist=True)
for patch, color in zip(bp['boxes'], COLORS):
    patch.set_facecolor(color)

Scatter plot

ax.scatter(x, y, c=colors, s=sizes, alpha=0.6, cmap='viridis')

6. File Management

Directory structure

figures/
├── chapter1/
│   ├── fig1_overview.py
│   ├── fig1_overview.png
│   └── fig1_overview.svg
├── chapter2/
└── chapter3/

Naming conventions

  • File name format:fig{序号}_{描述}.py
  • Example:fig1_model_architecture.py

7. Quality Check

Chart content

  • Data is accurate and correct
  • Axis labels are complete (including units)
  • Legend is clear and readable

Visual effect

  • Use top-journal color schemes
  • Resolution reaches 450 DPI
  • Font size is moderate

File output

  • PNG format has been generated
  • SVG format generated
  • File naming conventions

VIII. Common Issues

Q1: Chinese characters display as squares

from matplotlib.font_manager import FontProperties
font = FontProperties(fname='/System/Library/Fonts/STHeiti Light.ttc')
ax.set_xlabel('中文标签', fontproperties=font)

Q2: Images are blurry

plt.savefig('figure.png', dpi=450, bbox_inches='tight')

Q3: Legend obscures data

ax.legend(loc='upper left', bbox_to_anchor=(1.02, 1))