You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Seaborn绘制带连线的散点图展示各类别趋势?

使用Seaborn实现带连线与标注的趋势散点图

给定如下结构的DataFrame:

country    strength    index_name     index
africa     0.75        5A             5
boston     0.65        5A             5
tga        0.89        5A             5
ollaw      0.45        5A             5
africa     0.69        80A            80
boston     0.35        80A            80
tga        0.81        80A            80
ollaw      0.33        80A            80
pica       0.29        80A            80
africa     0.70        150A           150
boston     0.47        150A           150
tga        0.40        150A           150
FSD        0.90        150A           150

需求为:绘制散点图,每个点标注对应国家/城市名称,同时用连线连接同一国家/城市在不同index_name下的点,以展示其strength的变化趋势。


完全可以用Seaborn结合Matplotlib实现,步骤如下:

1. 数据准备

先将数据加载为Pandas DataFrame,确保index列是数值型(保证横轴排序正确):

import pandas as pd

data = [
    ["africa", 0.75, "5A", 5],
    ["boston", 0.65, "5A", 5],
    ["tga", 0.89, "5A", 5],
    ["ollaw", 0.45, "5A", 5],
    ["africa", 0.69, "80A", 80],
    ["boston", 0.35, "80A", 80],
    ["tga", 0.81, "80A", 80],
    ["ollaw", 0.33, "80A", 80],
    ["pica", 0.29, "80A", 80],
    ["africa", 0.70, "150A", 150],
    ["boston", 0.47, "150A", 150],
    ["tga", 0.40, "150A", 150],
    ["FSD", 0.90, "150A", 150],
]
df = pd.DataFrame(data, columns=["country", "strength", "index_name", "index"])
# 转换为数值类型,确保横轴按数值顺序排列
df["index"] = df["index"].astype(int)

2. 绘图实现

用Seaborn的lineplot绘制同一国家的连线,scatterplot绘制散点,再用Matplotlib的annotate添加点标注:

import seaborn as sns
import matplotlib.pyplot as plt

# 设置绘图风格
sns.set_style("whitegrid")
plt.figure(figsize=(10,6))

# 绘制同一国家的趋势连线:hue区分国家,关闭置信区间
sns.lineplot(data=df, x="index", y="strength", hue="country", ci=None, linestyle="-", linewidth=1.5)

# 绘制散点:放大点尺寸,zorder确保散点在连线之上
sns.scatterplot(data=df, x="index", y="strength", hue="country", s=100, zorder=5)

# 为每个点添加国家名称标注
for _, row in df.iterrows():
    plt.annotate(row["country"], 
                 (row["index"], row["strength"]),
                 xytext=(5,5),  # 标注偏移量,避免遮挡点
                 textcoords="offset points",
                 fontsize=9)

# 清理重复图例(lineplot和scatterplot会生成重复项)
handles, labels = plt.gca().get_legend_handles_labels()
unique_legend = dict(zip(labels, handles))
plt.legend(unique_legend.values(), unique_legend.keys(), bbox_to_anchor=(1.05, 1), loc="upper left")

# 设置坐标轴与标题
plt.xlabel("Index Value")
plt.ylabel("Strength")
plt.title("Strength Trend by Country/Across Indexes")

plt.tight_layout()
plt.show()

关键说明

  • lineplot的hue="country"参数会自动为每个国家绘制独立连线,确保同一国家的点按index顺序连接
  • zorder=5保证散点显示在连线之上,避免被遮挡
  • 通过annotate逐个添加点标注,xytext调整标注位置优化可读性
  • 最后清理重复图例,让图表布局更整洁

内容的提问来源于stack exchange,提问作者Obiii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:15:33