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

如何将Pandas DataFrame绘制成Layer拆分Exponent列的散点图?

问题描述

我有如下Pandas DataFrame:

layer   bit-idx exponent    accuracy
conv2d  0       0           0.683099
conv2d  1       0           0.683099
conv2d  2       0           0.683099
conv2d  3       0           0.683099
conv2d  0       1           0.682403
conv2d  1       1           0.668917
conv2d  2       1           0.472103
conv2d  3       1           0.668600
dense   0       0           0.683107
dense   1       0           0.683101
dense   2       0           0.683020
dense   3       0           0.513099
dense   0       1           0.683107
dense   1       1           0.683101
dense   2       1           0.483020
dense   3       1           0.553099

我最初尝试绘图的代码如下:

plt.grid()
ax = sns.scatterplot(data=df_bi, x='layer', y=df_bi['accuracy']*100, hue='index', alpha=1, s=100, palette='RdBu', legend=True)
sns.lineplot(data=df_wi, x='layer', y=68.3099, linestyle='--', color='red', linewidth=1, ax=ax)
plt.ylim(10,80)

现在需要绘制这样的散点图:X轴为layer,每个layer刻度下拆分为exponent=0和exponent=1两组,Y轴表示accuracy。


解决方案

方法一:利用dodge参数自动分组错开

Seaborn的scatterplot支持dodge=True参数,可自动将同一分类下不同hue分组的点错开,正好满足需求:

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(8, 6))
# 用hue区分exponent,dodge=True让同layer下的两组点错开
ax = sns.scatterplot(data=df, x='layer', y=df['accuracy']*100,
                     hue='exponent', style='bit-idx', s=100,
                     palette='RdBu', dodge=True)
# 添加基准线
plt.axhline(y=68.3099, linestyle='--', color='red', linewidth=1)
plt.ylim(10, 80)
plt.grid(True)
plt.ylabel('accuracy (%)')
plt.legend(title='exponent')
plt.show()

方法二:手动计算X轴偏移量

如果需要更精细的位置控制,可以手动给不同exponent的点添加X轴偏移:

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

# 将layer转为分类变量,获取编码值
df['layer_code'] = pd.Categorical(df['layer']).codes
# 给exponent=0和1分别分配偏移量
df['x_pos'] = df['layer_code'] + df['exponent'].map({0: -0.15, 1: 0.15})

plt.figure(figsize=(8, 6))
sns.scatterplot(data=df, x='x_pos', y=df['accuracy']*100,
                hue='exponent', style='bit-idx', s=100, palette='RdBu')
# 设置X轴刻度和标签
plt.xticks(ticks=df['layer_code'].unique(), labels=df['layer'].unique())
# 添加基准线
plt.axhline(y=68.3099, linestyle='--', color='red', linewidth=1)
plt.ylim(10, 80)
plt.grid(True)
plt.xlabel('layer')
plt.ylabel('accuracy (%)')
plt.legend(title='exponent')
plt.show()

说明:两种方法都能实现需求,方法一更简洁;方法二适合需要自定义偏移距离的场景。如果需要区分不同bit-idx的点,可通过style参数设置不同的点样式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:15:46