Back to skills
extension
Category: Data & AnalyticsNo API key required

数据可视化

SkillHub skill

personAuthor: user_3c6cb52ehubcommunity

Data Visualization

此技能使 AI agent 能够将结构化数据转换为有意义的视觉表示。agent 根据数据和所提问题选择适当的图表类型,使用 matplotlib 和 seaborn 构建出版质量的静态图表,并使用 plotly 创建交互式可视化。它遵循既定的数据可视化原则以确保清晰性、准确性和视觉吸引力。

Workflow

  1. 理解数据和问题。检查数据集结构——有多少变量,什么类型(数值型、分类型、时间型),以及用户希望突出的关系或比较。问题是图表选择的驱动力,而不仅仅是数据本身。

  2. 选择适当的图表类型。将分析目标与正确的视觉形式匹配。使用条形图进行分类比较,折线图展示时间趋势,散点图表示两个连续变量之间的关系,直方图显示分布,箱线图显示离散和异常值,热力图用于相关矩阵或密集分类网格。

  3. 为绘图准备数据。根据需要聚合、透视或重塑数据。对条形图的分类轴按值排序。对时间序列进行适当粒度的重采样。确保没有 NaN 值渗入图表中造成空白或错误。

  4. 使用适当的样式构建可视化。应用一致的颜色调色板、可读的轴标签、描述性标题和正确的图例。去除图表杂乱元素——不必要的网格线、边框和装饰。使用与预期输出媒介(报告、幻灯片、仪表板)匹配的图形尺寸。

  5. 添加上下文和注释。通过注释、参考线或着色区域突出关键数据点。在图表上直接添加摘要统计信息(如有帮助,例如箱线图中的中位数线、散点图中的趋势线)。上下文使图表从装饰变为分析。

  6. 导出或显示。将静态图表保存为 PNG 或 SVG 用于报告,或将交互式 HTML 渲染用于仪表板和探索。设置 DPI 至少为 150 以获得打印质量输出。

支持的技术

  • matplotlib — 全面控制每个视觉元素的基础绘图库
  • seaborn — 带有合理默认值和内置主题的统计可视化
  • plotly — 具有悬停提示、缩放和平移功能的交互式图表
  • plotly.express — 快速创建交互式图表的简洁 API

何时使用哪种图表类型

| Goal | Chart Type | Library | |------|-----------|---------| | Compare categories | Bar chart (vertical or horizontal) | matplotlib, seaborn | | Show trend over time | Line chart | matplotlib, plotly | | Explore relationship between 2 variables | Scatter plot | seaborn, plotly | | Show distribution of a variable | Histogram or KDE | seaborn | | Compare distributions across groups | Box plot or violin plot | seaborn | | Display correlation matrix | Heatmap | seaborn | | Show composition / proportions | Stacked bar or pie chart | matplotlib | | Enable user exploration | Interactive chart | plotly |

Usage

向 agent 提供数据集和你想要可视化的描述。可选择性地指定图表类型、颜色偏好、输出格式和图形尺寸。如果未指定图表类型,agent 将选择最佳方法。

Examples

示例 1:使用 matplotlib 和 seaborn 的销售仪表板

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.read_csv("quarterly_sales.csv", parse_dates=["date"])
sns.set_theme(style="whitegrid", palette="viridis")

fig, axes = plt.subplots(2, 2, figsize=(14, 10))
fig.suptitle("Q4 2024 Sales Dashboard", fontsize=16, fontweight="bold")

# 1. Monthly revenue trend
monthly = df.resample("M", on="date")["revenue"].sum()
axes[0, 0].plot(monthly.index, monthly.values, marker="o", linewidth=2)
axes[0, 0].set_title("Monthly Revenue Trend")
axes[0, 0].set_ylabel("Revenue ($)")
axes[0, 0].tick_params(axis="x", rotation=45)

# 2. Revenue by region (horizontal bar)
region = df.groupby("region")["revenue"].sum().sort_values()
axes[0, 1].barh(region.index, region.values, color=sns.color_palette("viridis", len(region)))
axes[0, 1].set_title("Revenue by Region")
axes[0, 1].set_xlabel("Total Revenue ($)")

# 3. Units sold distribution (histogram)
axes[1, 0].hist(df["units_sold"], bins=30, edgecolor="white", alpha=0.8)
axes[1, 0].axvline(df["units_sold"].median(), color="red", linestyle="--", label="Median")
axes[1, 0].set_title("Units Sold Distribution")
axes[1, 0].legend()

# 4. Revenue vs. discount scatter with regression
sns.regplot(data=df, x="discount", y="revenue", ax=axes[1, 1],
            scatter_kws={"alpha": 0.4, "s": 15}, line_kws={"color": "red"})
axes[1, 1].set_title("Revenue vs. Discount")

plt.tight_layout()
plt.savefig("sales_dashboard.png", dpi=150, bbox_inches="tight")
plt.show()

示例 2:使用 plotly 的交互式可视化

import pandas as pd
import plotly.express as px

df = pd.read_csv("global_sales.csv")

# Interactive scatter with size, color, and hover data
fig = px.scatter(
    df,
    x="marketing_spend",
    y="revenue",
    size="units_sold",
    color="region",
    hover_data=["product_name", "quarter"],
    title="Marketing Spend vs Revenue by Region",
    labels={
        "marketing_spend": "Marketing Spend ($)",
        "revenue": "Revenue ($)",
        "units_sold": "Units Sold"
    },
    template="plotly_white"
)

fig.update_traces(marker=dict(opacity=0.7, line=dict(width=1, color="DarkSlateGrey")))

# Add a trend line annotation
fig.add_annotation(
    x=45000, y=320000,
    text="Strong ROI cluster:<br>low spend, high revenue",
    showarrow=True, arrowhead=2,
    font=dict(size=12, color="darkblue")
)

fig.write_html("interactive_scatter.html")
fig.show()
# Users can hover over points to see product_name and quarter,
# zoom into clusters, and toggle regions on/off via the legend.

最佳实践

  • 根据分析问题选择图表类型,而非美观性 —— 即使散点图未显示模式,如果问题是关于相关性的,它仍然是正确选择。
  • 将颜色类别限制在 7 种或更少;超出此范围时使用分面或小多重图代替将更多颜色塞入单一图例。
  • 总是用单位标注轴,并使用人类可读的数字格式(例如,“$1.2M”而不是“1200000”)。
  • 条形图 y 轴从零开始以避免夸大差异;当关注变化而非绝对值时,折线图可以使用截断轴。
  • 默认使用色盲友好调色板(viridis、cividis 或 ColorBrewer 定性集合)。
  • 任何将出现在文档或演示中的图表都应以 150+ DPI 导出。

Edge Cases

  • 单个图表类别过多。如果条形图将超过 15 个条形,则显示前 N 个并把其余归入“其他”类别,或者切换到树状图。
  • 散点图中的重叠点。当数千个点重叠时使用透明度(alpha=0.3)、抖动或六边形/二维密度图。
  • 轴标签过长。将标签旋转 45 度、用省略号截断,或切换到水平条形图以保持文本可读性。
  • 缺失值导致折线图出现间隙。对小间隙(1-2 个点)进行线性插值并用虚线段标记;对于较大间隙,断开线条以避免暗示连续性。
  • 极度偏斜的数据。应用对数刻度轴并在轴标签中清楚注明转换(例如,“收入(对数刻度)”)。