[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-944fed53-c763-492c-8c1e-5409623363f3":3,"$fNlnOv0iy3sKUBP0HTDdAUZH7qvEAJS8_xj9wPlQeIA8":43},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":34},"944fed53-c763-492c-8c1e-5409623363f3","matplotlib","Matplotlib是Python创建静态、动画和交互式图表的基础可视化库。","cat_prod_data","mod_productivity","sickn33,productivity","---\nname: matplotlib\ndescription: \"Matplotlib is Python's foundational visualization library for creating static, animated, and interactive plots.\"\nlicense: https:\u002F\u002Fgithub.com\u002Fmatplotlib\u002Fmatplotlib\u002Ftree\u002Fmain\u002FLICENSE\nmetadata:\n    skill-author: K-Dense Inc.\nrisk: unknown\nsource: community\n---\n\n# Matplotlib\n\n## Overview\n\nMatplotlib is Python's foundational visualization library for creating static, animated, and interactive plots. This skill provides guidance on using matplotlib effectively, covering both the pyplot interface (MATLAB-style) and the object-oriented API (Figure\u002FAxes), along with best practices for creating publication-quality visualizations.\n\n## When to Use This Skill\n\nThis skill should be used when:\n- Creating any type of plot or chart (line, scatter, bar, histogram, heatmap, contour, etc.)\n- Generating scientific or statistical visualizations\n- Customizing plot appearance (colors, styles, labels, legends)\n- Creating multi-panel figures with subplots\n- Exporting visualizations to various formats (PNG, PDF, SVG, etc.)\n- Building interactive plots or animations\n- Working with 3D visualizations\n- Integrating plots into Jupyter notebooks or GUI applications\n\n## Core Concepts\n\n### The Matplotlib Hierarchy\n\nMatplotlib uses a hierarchical structure of objects:\n\n1. **Figure** - The top-level container for all plot elements\n2. **Axes** - The actual plotting area where data is displayed (one Figure can contain multiple Axes)\n3. **Artist** - Everything visible on the figure (lines, text, ticks, etc.)\n4. **Axis** - The number line objects (x-axis, y-axis) that handle ticks and labels\n\n### Two Interfaces\n\n**1. pyplot Interface (Implicit, MATLAB-style)**\n```python\nimport matplotlib.pyplot as plt\n\nplt.plot([1, 2, 3, 4])\nplt.ylabel('some numbers')\nplt.show()\n```\n- Convenient for quick, simple plots\n- Maintains state automatically\n- Good for interactive work and simple scripts\n\n**2. Object-Oriented Interface (Explicit)**\n```python\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nax.plot([1, 2, 3, 4])\nax.set_ylabel('some numbers')\nplt.show()\n```\n- **Recommended for most use cases**\n- More explicit control over figure and axes\n- Better for complex figures with multiple subplots\n- Easier to maintain and debug\n\n## Common Workflows\n\n### 1. Basic Plot Creation\n\n**Single plot workflow:**\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Create figure and axes (OO interface - RECOMMENDED)\nfig, ax = plt.subplots(figsize=(10, 6))\n\n# Generate and plot data\nx = np.linspace(0, 2*np.pi, 100)\nax.plot(x, np.sin(x), label='sin(x)')\nax.plot(x, np.cos(x), label='cos(x)')\n\n# Customize\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_title('Trigonometric Functions')\nax.legend()\nax.grid(True, alpha=0.3)\n\n# Save and\u002For display\nplt.savefig('plot.png', dpi=300, bbox_inches='tight')\nplt.show()\n```\n\n### 2. Multiple Subplots\n\n**Creating subplot layouts:**\n```python\n# Method 1: Regular grid\nfig, axes = plt.subplots(2, 2, figsize=(12, 10))\naxes[0, 0].plot(x, y1)\naxes[0, 1].scatter(x, y2)\naxes[1, 0].bar(categories, values)\naxes[1, 1].hist(data, bins=30)\n\n# Method 2: Mosaic layout (more flexible)\nfig, axes = plt.subplot_mosaic([['left', 'right_top'],\n                                 ['left', 'right_bottom']],\n                                figsize=(10, 8))\naxes['left'].plot(x, y)\naxes['right_top'].scatter(x, y)\naxes['right_bottom'].hist(data)\n\n# Method 3: GridSpec (maximum control)\nfrom matplotlib.gridspec import GridSpec\nfig = plt.figure(figsize=(12, 8))\ngs = GridSpec(3, 3, figure=fig)\nax1 = fig.add_subplot(gs[0, :])  # Top row, all columns\nax2 = fig.add_subplot(gs[1:, 0])  # Bottom two rows, first column\nax3 = fig.add_subplot(gs[1:, 1:])  # Bottom two rows, last two columns\n```\n\n### 3. Plot Types and Use Cases\n\n**Line plots** - Time series, continuous data, trends\n```python\nax.plot(x, y, linewidth=2, linestyle='--', marker='o', color='blue')\n```\n\n**Scatter plots** - Relationships between variables, correlations\n```python\nax.scatter(x, y, s=sizes, c=colors, alpha=0.6, cmap='viridis')\n```\n\n**Bar charts** - Categorical comparisons\n```python\nax.bar(categories, values, color='steelblue', edgecolor='black')\n# For horizontal bars:\nax.barh(categories, values)\n```\n\n**Histograms** - Distributions\n```python\nax.hist(data, bins=30, edgecolor='black', alpha=0.7)\n```\n\n**Heatmaps** - Matrix data, correlations\n```python\nim = ax.imshow(matrix, cmap='coolwarm', aspect='auto')\nplt.colorbar(im, ax=ax)\n```\n\n**Contour plots** - 3D data on 2D plane\n```python\ncontour = ax.contour(X, Y, Z, levels=10)\nax.clabel(contour, inline=True, fontsize=8)\n```\n\n**Box plots** - Statistical distributions\n```python\nax.boxplot([data1, data2, data3], labels=['A', 'B', 'C'])\n```\n\n**Violin plots** - Distribution densities\n```python\nax.violinplot([data1, data2, data3], positions=[1, 2, 3])\n```\n\nFor comprehensive plot type examples and variations, refer to `references\u002Fplot_types.md`.\n\n### 4. Styling and Customization\n\n**Color specification methods:**\n- Named colors: `'red'`, `'blue'`, `'steelblue'`\n- Hex codes: `'#FF5733'`\n- RGB tuples: `(0.1, 0.2, 0.3)`\n- Colormaps: `cmap='viridis'`, `cmap='plasma'`, `cmap='coolwarm'`\n\n**Using style sheets:**\n```python\nplt.style.use('seaborn-v0_8-darkgrid')  # Apply predefined style\n# Available styles: 'ggplot', 'bmh', 'fivethirtyeight', etc.\nprint(plt.style.available)  # List all available styles\n```\n\n**Customizing with rcParams:**\n```python\nplt.rcParams['font.size'] = 12\nplt.rcParams['axes.labelsize'] = 14\nplt.rcParams['axes.titlesize'] = 16\nplt.rcParams['xtick.labelsize'] = 10\nplt.rcParams['ytick.labelsize'] = 10\nplt.rcParams['legend.fontsize'] = 12\nplt.rcParams['figure.titlesize'] = 18\n```\n\n**Text and annotations:**\n```python\nax.text(x, y, 'annotation', fontsize=12, ha='center')\nax.annotate('important point', xy=(x, y), xytext=(x+1, y+1),\n            arrowprops=dict(arrowstyle='->', color='red'))\n```\n\nFor detailed styling options and colormap guidelines, see `references\u002Fstyling_guide.md`.\n\n### 5. Saving Figures\n\n**Export to various formats:**\n```python\n# High-resolution PNG for presentations\u002Fpapers\nplt.savefig('figure.png', dpi=300, bbox_inches='tight', facecolor='white')\n\n# Vector format for publications (scalable)\nplt.savefig('figure.pdf', bbox_inches='tight')\nplt.savefig('figure.svg', bbox_inches='tight')\n\n# Transparent background\nplt.savefig('figure.png', dpi=300, bbox_inches='tight', transparent=True)\n```\n\n**Important parameters:**\n- `dpi`: Resolution (300 for publications, 150 for web, 72 for screen)\n- `bbox_inches='tight'`: Removes excess whitespace\n- `facecolor='white'`: Ensures white background (useful for transparent themes)\n- `transparent=True`: Transparent background\n\n### 6. Working with 3D Plots\n\n```python\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure(figsize=(10, 8))\nax = fig.add_subplot(111, projection='3d')\n\n# Surface plot\nax.plot_surface(X, Y, Z, cmap='viridis')\n\n# 3D scatter\nax.scatter(x, y, z, c=colors, marker='o')\n\n# 3D line plot\nax.plot(x, y, z, linewidth=2)\n\n# Labels\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\n```\n\n## Best Practices\n\n### 1. Interface Selection\n- **Use the object-oriented interface** (fig, ax = plt.subplots()) for production code\n- Reserve pyplot interface for quick interactive exploration only\n- Always create figures explicitly rather than relying on implicit state\n\n### 2. Figure Size and DPI\n- Set figsize at creation: `fig, ax = plt.subplots(figsize=(10, 6))`\n- Use appropriate DPI for output medium:\n  - Screen\u002Fnotebook: 72-100 dpi\n  - Web: 150 dpi\n  - Print\u002Fpublications: 300 dpi\n\n### 3. Layout Management\n- Use `constrained_layout=True` or `tight_layout()` to prevent overlapping elements\n- `fig, ax = plt.subplots(constrained_layout=True)` is recommended for automatic spacing\n\n### 4. Colormap Selection\n- **Sequential** (viridis, plasma, inferno): Ordered data with consistent progression\n- **Diverging** (coolwarm, RdBu): Data with meaningful center point (e.g., zero)\n- **Qualitative** (tab10, Set3): Categorical\u002Fnominal data\n- Avoid rainbow colormaps (jet) - they are not perceptually uniform\n\n### 5. Accessibility\n- Use colorblind-friendly colormaps (viridis, cividis)\n- Add patterns\u002Fhatching for bar charts in addition to colors\n- Ensure sufficient contrast between elements\n- Include descriptive labels and legends\n\n### 6. Performance\n- For large datasets, use `rasterized=True` in plot calls to reduce file size\n- Use appropriate data reduction before plotting (e.g., downsample dense time series)\n- For animations, use blitting for better performance\n\n### 7. Code Organization\n```python\n# Good practice: Clear structure\ndef create_analysis_plot(data, title):\n    \"\"\"Create standardized analysis plot.\"\"\"\n    fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)\n\n    # Plot data\n    ax.plot(data['x'], data['y'], linewidth=2)\n\n    # Customize\n    ax.set_xlabel('X Axis Label', fontsize=12)\n    ax.set_ylabel('Y Axis Label', fontsize=12)\n    ax.set_title(title, fontsize=14, fontweight='bold')\n    ax.grid(True, alpha=0.3)\n\n    return fig, ax\n\n# Use the function\nfig, ax = create_analysis_plot(my_data, 'My Analysis')\nplt.savefig('analysis.png', dpi=300, bbox_inches='tight')\n```\n\n## Quick Reference Scripts\n\nThis skill includes helper scripts in the `scripts\u002F` directory:\n\n### `plot_template.py`\nTemplate script demonstrating various plot types with best practices. Use this as a starting point for creating new visualizations.\n\n**Usage:**\n```bash\npython scripts\u002Fplot_template.py\n```\n\n### `style_configurator.py`\nInteractive utility to configure matplotlib style preferences and generate custom style sheets.\n\n**Usage:**\n```bash\npython scripts\u002Fstyle_configurator.py\n```\n\n## Detailed References\n\nFor comprehensive information, consult the reference documents:\n\n- **`references\u002Fplot_types.md`** - Complete catalog of plot types with code examples and use cases\n- **`references\u002Fstyling_guide.md`** - Detailed styling options, colormaps, and customization\n- **`references\u002Fapi_reference.md`** - Core classes and methods reference\n- **`references\u002Fcommon_issues.md`** - Troubleshooting guide for common problems\n\n## Integration with Other Tools\n\nMatplotlib integrates well with:\n- **NumPy\u002FPandas** - Direct plotting from arrays and DataFrames\n- **Seaborn** - High-level statistical visualizations built on matplotlib\n- **Jupyter** - Interactive plotting with `%matplotlib inline` or `%matplotlib widget`\n- **GUI frameworks** - Embedding in Tkinter, Qt, wxPython applications\n\n## Common Gotchas\n\n1. **Overlapping elements**: Use `constrained_layout=True` or `tight_layout()`\n2. **State confusion**: Use OO interface to avoid pyplot state machine issues\n3. **Memory issues with many figures**: Close figures explicitly with `plt.close(fig)`\n4. **Font warnings**: Install fonts or suppress warnings with `plt.rcParams['font.sans-serif']`\n5. **DPI confusion**: Remember that figsize is in inches, not pixels: `pixels = dpi * inches`\n\n## Additional Resources\n\n- Official documentation: https:\u002F\u002Fmatplotlib.org\u002F\n- Gallery: https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Fgallery\u002Findex.html\n- Cheatsheets: https:\u002F\u002Fmatplotlib.org\u002Fcheatsheets\u002F\n- Tutorials: https:\u002F\u002Fmatplotlib.org\u002Fstable\u002Ftutorials\u002Findex.html\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,199,143,"2026-05-16 13:28:11",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"效率工具","productivity","mdi-lightning-bolt-outline","文档处理、数据分析、自动化工作流",4,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":32,"skillCount":33,"createdAt":26},"数据分析","data-analysis","mdi-chart-bar","数据可视化、统计分析",2,30,[35],{"id":36,"skillId":4,"version":37,"fileName":38,"fileSize":39,"filePath":40,"fileHash":41,"manifest":42,"createdAt":19},"c28ea085-e2e9-4ab6-8305-a16bab21ab3c","1.0.0","matplotlib.zip",4769,"uploads\u002Fskills\u002F944fed53-c763-492c-8c1e-5409623363f3\u002Fmatplotlib.zip","9164a06b94c489d438591058a660ca09daf4aff8bc3914390af58b49cb394cab","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":11517}]",{"code":44,"message":45,"data":46},200,"success",{"items":47,"stats":48,"page":51},[],{"averageRating":49,"totalRatings":49,"ratingCounts":50},0,[49,49,49,49,49],{"limit":52,"offset":49,"hasMore":53,"nextOffset":52,"ratedOnly":16},15,false]