关于 data-visualization
用于通过 matplotlib 和 seaborn 创建分析图表的技能,适合数据分析与模型结果展示。它规定了无头渲染、PNG 导出和内联显示的流程。
主要功能
- 01绘制柱状图、折线图、散点图和热图
- 02绘制直方图和箱线图
- 03制作多面板分析摘要
- 04导出图表并内联显示
适用场景
- 01绘制 cuDF 分析结果
- 02可视化 cuML 模型发现
- 03用图表呈现统计结果
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ langchain-ai/ deepagents --skill data-visualization安装后在 Claude Code 中输入/data-visualization确认已加载。
详细介绍
数据可视化技能
在无头 GPU 沙箱中,使用 matplotlib 和 seaborn 创建可用于出版的分析图表。图表以 PNG 文件形式保存到 /workspace/,以便获取。
何时使用此技能
在以下情况使用此技能:
- 可视化 cuDF 分析或 cuML 模型的结果
- 创建图表(柱状图、折线图、散点图、热力图、直方图、箱线图)
- 构建多面板分析摘要
- 用户要求可视化输出、绘图、图形或图表
- 用图形展示统计结论
初始化(必需)
必须在导入 pyplot 之前调用 matplotlib.use('Agg')。这样可以启用无头渲染。
import matplotlib
matplotlib.use('Agg') # Headless backend — MUST be before pyplot import
import matplotlib.pyplot as plt
import numpy as np
# Publication-quality defaults
plt.rcParams.update({
'figure.dpi': 100,
'savefig.dpi': 300,
'font.size': 11,
'axes.labelsize': 12,
'axes.titlesize': 14,
'xtick.labelsize': 10,
'ytick.labelsize': 10,
'legend.fontsize': 10,
'figure.constrained_layout.use': True,
})
# Colorblind-safe palette (Okabe-Ito)
COLORS = ['#0173B2', '#DE8F05', '#029E73', '#D55E00', '#CC78BC',
'#CA9161', '#FBAFE4', '#949494', '#ECE133', '#56B4E9']
保存图表
始终使用以下设置保存到 /workspace/:
plt.savefig('/workspace/chart_name.png', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
plt.close()
# IMPORTANT: call read_file("/workspace/<chart>.png") to display inline
dpi=300以满足印刷质量bbox_inches='tight'去除多余空白facecolor='white'确保白色背景- 保存后始终调用
plt.close()以释放内存
展示图表(必需)
保存任何图表后,必须对其调用 read_file,以便在对话中内联显示:
read_file("/workspace/chart_name.png")
除非你这样做,否则用户无法看到图表。你保存的每个图表都必须紧跟一次 read_file 调用。
快速参考
柱状图(来自 groupby 结果)
# After: result = to_pd(df.groupby("category")["value"].mean())
fig, ax = plt.subplots(figsize=(8, 5))
bars = ax.bar(result.index, result.values, color=COLORS[:len(result)],
edgecolor='black', linewidth=0.8)
for bar in bars:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.1f}', ha='center', va='bottom', fontsize=9)
ax.set_ylabel('Mean Value', fontweight='bold')
ax.set_xlabel('Category', fontweight='bold')
ax.set_title('Average Value by Category', fontweight='bold')
ax.grid(axis='y', alpha=0.3, linestyle='--')
ax.set_axisbelow(True)
plt.savefig('/workspace/bar_chart.png', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
plt.close()
# IMPORTANT: call read_file("/workspace/<chart>.png") to display inline
折线图(随时间变化的趋势)
fig, ax = plt.subplots(figsize=(10, 5))
for i, col in enumerate(columns_to_plot):
ax.plot(df["date"], df[col], label=col, color=COLORS[i], linewidth=2,
marker='o', markersize=3, markevery=max(1, len(df)//20))
ax.set_ylabel('Values', fontweight='bold')
ax.set_xlabel('Date', fontweight='bold')
ax.set_title('Trends Over Time', fontweight='bold')
ax.legend(frameon=True, shadow=False)
ax.grid(True, alpha=0.3, linestyle='--')
ax.set_axisbelow(True)
plt.xticks(rotation=45, ha='right')
plt.savefig('/workspace/line_chart.png', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
plt.close()
# IMPORTANT: call read_file("/workspace/<chart>.png") to display inline
散点图 — 连续颜色(相关性)
fig, ax = plt.subplots(figsize=(8, 6))
scatter = ax.scatter(df["x"], df["y"], c=df["value"], cmap='viridis',
s=40, alpha=0.7, edgecolors='black', linewidth=0.3)
plt.colorbar(scatter, ax=ax, label='Value')
# Optional: trend line
z = np.polyfit(df["x"], df["y"], 1)
ax.plot(df["x"].sort_values(), np.poly1d(z)(df["x"].sort_values()),
"r--", linewidth=2, label=f'y={z[0]:.2f}x+{z[1]:.2f}')
ax.set_xlabel('X', fontweight='bold')
ax.set_ylabel('Y', fontweight='bold')
ax.set_title('Correlation Analysis', fontweight='bold')
ax.legend()
ax.grid(True, alpha=0.3, linestyle='--')
plt.savefig('/workspace/scatter_correlation.png', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
plt.close()
# IMPORTANT: call read_file("/workspace/<chart>.png") to display inline
散点图 — 分类颜色(聚类)
fig, ax = plt.subplots(figsize=(8, 6))
for i, label in enumerate(sorted(df["cluster"].unique())):
mask = df["cluster"] == label
ax.scatter(df.loc[mask, "x"], df.loc[mask, "y"],
c=COLORS[i], label=f'Cluster {label}', s=40, alpha=0.7)
ax.set_xlabel('X', fontweight='bold')
ax.set_ylabel('Y', fontweight='bold')
ax.set_title('Cluster Visualization', fontweight='bold')
ax.legend()
ax.grid(True, alpha=0.3, linestyle='--')
plt.savefig('/workspace/scatter_clusters.png', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
plt.close()
# IMPORTANT: call read_file("/workspace/<chart>.png") to display inline
热力图(相关矩阵或混淆矩阵)
import seaborn as sns
fig, ax = plt.subplots(figsize=(8, 7))
# corr_matrix = to_pd(df[numeric_cols].corr())
sns.heatmap(corr_matrix, annot=True, fmt='.2f', cmap='RdBu_r', center=0,
square=True, linewidths=1, vmin=-1, vmax=1,
cbar_kws={'label': 'Correlation'}, ax=ax)
ax.set_title('Correlation Matrix', fontweight='bold')
plt.savefig('/workspace/heatmap.png', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
plt.close()
# IMPORTANT: call read_file("/workspace/<chart>.png") to display inline
带 KDE 的直方图
fig, ax = plt.subplots(figsize=(8, 5))
ax.hist(df["value"], bins=30, color=COLORS[0], alpha=0.7,
edgecolor='black', linewidth=0.5, density=True, label='Distribution')
# Add KDE curve
from scipy.stats import gaussian_kde
kde = gaussian_kde(df["value"].dropna())
x_range = np.linspace(df["value"].min(), df["value"].max(), 200)
ax.plot(x_range, kde(x_range), color=COLORS[1], linewidth=2, label='KDE')
ax.set_xlabel('Value', fontweight='bold')
ax.set_ylabel('Density', fontweight='bold')
ax.set_title('Value Distribution', fontweight='bold')
ax.legend()
ax.grid(axis='y', alpha=0.3, linestyle='--')
plt.savefig('/workspace/histogram.png', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
plt.close()
# IMPORTANT: call read_file("/workspace/<chart>.png") to display inline
箱线图(比较各组)
fig, ax = plt.subplots(figsize=(8, 5))
groups = [df[df["group"] == g]["value"].values for g in group_names]
bp = ax.boxplot(groups, labels=group_names, patch_artist=True,
widths=0.6, showmeans=True,
meanprops=dict(marker='D', markerfacecolor='red', markersize=6))
for i, patch in enumerate(bp['boxes']):
patch.set_facecolor(COLORS[i % len(COLORS)])
patch.set_alpha(0.7)
ax.set_ylabel('Value', fontweight='bold')
ax.set_title('Distribution by Group', fontweight='bold')
ax.grid(axis='y', alpha=0.3, linestyle='--')
ax.set_axisbelow(True)
plt.savefig('/workspace/boxplot.png', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
plt.close()
# IMPORTANT: call read_file("/workspace/<chart>.png") to display inline
多面板分析摘要
使用此方法可将多个图表合并到一张图像中,这是展示完整分析最有效的方式。
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# Top-left: Distribution
axes[0, 0].hist(df["value"], bins=30, color=COLORS[0], alpha=0.7, edgecolor='black', linewidth=0.5)
axes[0, 0].set_title('Value Distribution', fontweight='bold')
axes[0, 0].set_xlabel('Value')
axes[0, 0].grid(axis='y', alpha=0.3, linestyle='--')
# Top-right: Scatter
axes[0, 1].scatter(df["x"], df["y"], c=COLORS[0], s=30, alpha=0.5)
axes[0, 1].set_title('X vs Y', fontweight='bold')
axes[0, 1].set_xlabel('X')
axes[0, 1].set_ylabel('Y')
axes[0, 1].grid(True, alpha=0.3, linestyle='--')
# Bottom-left: Bar chart
group_means = df.groupby("category")["value"].mean()
axes[1, 0].bar(group_means.index, group_means.values, color=COLORS[:len(group_means)])
axes[1, 0].set_title('Mean by Category', fontweight='bold')
axes[1, 0].set_xlabel('Category')
axes[1, 0].grid(axis='y', alpha=0.3, linestyle='--')
# Bottom-right: Box plot
axes[1, 1].boxplot([df[df["category"] == c]["value"].values for c in categories],
labels=categories, patch_artist=True)
axes[1, 1].set_title('Distribution by Category', fontweight='bold')
axes[1, 1].grid(axis='y', alpha=0.3, linestyle='--')
fig.suptitle('Analysis Summary', fontsize=16, fontweight='bold')
plt.savefig('/workspace/analysis_summary.png', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
plt.close()
# IMPORTANT: call read_file("/workspace/<chart>.png") to display inline
特征重要性图(来自 cuML 模型)
fig, ax = plt.subplots(figsize=(8, max(4, len(feature_names) * 0.35)))
# importances = to_pd(model.feature_importances_)
sorted_idx = np.argsort(importances)
ax.barh(np.array(feature_names)[sorted_idx], importances[sorted_idx],
color=COLORS[0], edgecolor='black', linewidth=0.5)
ax.set_xlabel('Importance', fontweight='bold')
ax.set_title('Feature Importances', fontweight='bold')
ax.grid(axis='x', alpha=0.3, linestyle='--')
ax.set_axisbelow(True)
plt.savefig('/workspace/feature_importance.png', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
plt.close()
# IMPORTANT: call read_file("/workspace/<chart>.png") to display inline
混淆矩阵(来自 cuML 分类)
import seaborn as sns
fig, ax = plt.subplots(figsize=(7, 6))
# cm = confusion_matrix(to_pd(y_test), to_pd(predictions))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', square=True,
xticklabels=class_names, yticklabels=class_names,
linewidths=1, cbar_kws={'label': 'Count'}, ax=ax)
ax.set_xlabel('Predicted', fontweight='bold')
ax.set_ylabel('Actual', fontweight='bold')
ax.set_title('Confusion Matrix', fontweight='bold')
plt.savefig('/workspace/confusion_matrix.png', dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
plt.close()
# IMPORTANT: call read_file("/workspace/<chart>.png") to display inline
样式规则
- 使用
COLORS调色板(色盲友好)— 不要仅依靠颜色来区分元素 - 不使用饼图(柱状图始终更清晰)
- 不使用 3D 图(会扭曲数据感知)
- 网格线使用
alpha=0.3, linestyle='--',并设置ax.set_axisbelow(True) - 坐标轴标签和标题加粗(
fontweight='bold') - 所有导出图像使用白色背景
- 每次分析通常使用 1-4 个图表;更多时使用多面板
输出指南
- 将所有图表以 PNG 格式保存到
/workspace/ - 保存后打印文件路径,以便 Agent 引用
- 对于多面板摘要,2×2 布局使用
figsize=(14, 10) - 图表标题应描述性强但简洁
- 适用时在坐标轴标签中包含单位
评论
支持 Markdown