matplotlib 如何以不同颜色绘制散点图并添加图例

ncgqoxb0  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(240)

从下面的df中,我提取了所需的行

**name**  **event**        **X**         **Y**
peter       run             20             50
peter       jog             30             25
peter       swim            21             22 
peter       walk            28             32
jon         swim            20             51

我运行了以下代码

mask_activity = df.event.isin (['run','jog','swim']) & (df.name == "peter")
                                                     
df_activity = df.loc[mask_activity, ['X','Y']]

我想用三种不同的颜色在一张叫做音高的Map中绘制这些动作,并在上面添加一个图例

pitch = Pitch(line_color='black')
fig, ax = pitch.grid(grid_height=0.9, title_height=0.06, axis=False, 
                     endnote_height=0.04, title_space=0, endnote_space=0)

pitch.scatter(df_activity.x, df_activity.y, alpha = 1, s = 500, color = "blue", ax=ax['pitch'])
fig.suptitle("activity", fontsize = 30)

plt.show()
z31licg0

z31licg01#

事件名称被添加到形成散点图基础的数据中,并且数据框被循环以通过关联事件和颜色来绘制图形。如果标签设置为事件名称,则它将显示在图例设置中。由于标记大小较大,图例中标签之间的间距将被调整。

mask_activity = df.event.isin (['run','jog','swim']) & (df.name == "peter")                                       
df_activity = df.loc[mask_activity, ['event','X','Y']]

df_activity
    event   X   Y
0   run     20  50
1   jog     30  25
2   swim    21  22

import matplotlib.pyplot as plt
from mplsoccer import Pitch, VerticalPitch

pitch = Pitch(line_color='black')
fig, ax = pitch.grid(grid_height=0.9, title_height=0.06, axis=False, 
                     endnote_height=0.04, title_space=0, endnote_space=0)

colors = {'run': 'blue', 'jog': 'green', 'swim': 'red'}
for row in df_activity.itertuples():
    c = colors[row[1]]
    pitch.scatter(row[2], row[3], alpha = 1, s = 500, color = c, label=row[1], ax=ax['pitch'])

fig.suptitle("activity", fontsize = 30)
ax['pitch'].legend(labelspacing=2)
plt.show()

相关问题