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

如何基于示例DataFrame绘制x轴为列名、点形状随索引变化的散点图

解决方案

要实现你需要的散点图,核心是先将宽格式的DataFrame转换为长格式,再按索引(类别)分配不同的点形状,具体步骤如下:

1. 导入依赖库

import pandas as pd
import matplotlib.pyplot as plt
# 可选:用seaborn简化绘图流程
import seaborn as sns

2. 准备示例数据

data = {'Column 1' : [1., 2., 3., 4.],
        'Column 2' : [1.2, 2.2, 3.2, 4.2]
       }
df = pd.DataFrame(data, index=["Apples", "Oranges", "Puppies", "Ducks"])

3. 转换数据格式

将宽格式转为长格式,让列名成为独立的Column列,索引成为Category列,方便后续映射x轴和点样式:

df_long = df.reset_index().rename(columns={'index': 'Category'}).melt(
    id_vars='Category', 
    var_name='Column', 
    value_name='Value'
)

4. 定义点形状映射

给每个索引(类别)分配独特的标记样式:

marker_map = {
    'Apples': 'o',    # 圆形
    'Oranges': 's',   # 正方形
    'Puppies': '^',   # 三角形
    'Ducks': 'D'      # 菱形
}

5. 绘制散点图

方法一:Matplotlib原生绘图

plt.figure(figsize=(8, 5))
# 按类别分组绘制不同形状的点
for category, group in df_long.groupby('Category'):
    plt.scatter(
        x=group['Column'], 
        y=group['Value'], 
        marker=marker_map[category], 
        label=category,
        s=120  # 控制点的大小
    )

# 添加图表元素
plt.xlabel('列名')
plt.ylabel('数值')
plt.title('按类别区分点形状的散点图')
plt.legend(title='类别')
plt.show()

方法二:Seaborn简化绘图

Seaborn可直接通过style参数绑定类别,自动应用标记样式:

plt.figure(figsize=(8, 5))
sns.scatterplot(
    data=df_long,
    x='Column',
    y='Value',
    style='Category',
    markers=marker_map,
    s=120
)

# 添加图表元素
plt.xlabel('列名')
plt.ylabel('数值')
plt.title('按类别区分点形状的散点图')
plt.legend(title='类别')
plt.show()

以上两种方法都能生成符合要求的散点图:x轴为列名,每个索引对应的点使用不同形状区分。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:15:24