Python 向动画散点图添加图例

Python 向动画散点图添加图例,python,python-3.x,animation,matplotlib,scatter-plot,Python,Python 3.x,Animation,Matplotlib,Scatter Plot,我正在制作一个带有散点图的动画,该散点图显示了随时间变化的多个组的数据。 当我想添加图例时,我能得到的最好结果只能显示一个组。 样本数据集: import pandas as pd df = pd.DataFrame([ [1, 'a', 0.39, 0.73], [1, 'b', 0.87, 0.94], [1, 'c', 0.87, 0.23], [2, 'a', 0.17, 0.37], [2, 'b', 0.03, 0.12], [2,

我正在制作一个带有散点图的动画,该散点图显示了随时间变化的多个组的数据。
当我想添加图例时,我能得到的最好结果只能显示一个组。
样本数据集:

import pandas as pd 

df = pd.DataFrame([
    [1, 'a', 0.39, 0.73],
    [1, 'b', 0.87, 0.94],
    [1, 'c', 0.87, 0.23],
    [2, 'a', 0.17, 0.37],
    [2, 'b', 0.03, 0.12],
    [2, 'c', 0.86, 0.22],
    [3, 'a', 0.01, 0.15],
    [3, 'b', 0.03, 0.1],
    [3, 'c', 0.29, 0.19],
    columns=['period', 'group', 'x', 'y']
)
我的动画是这样构建的:

import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
colors = {
'a': 'r',
'b': 'b',
'c': 'g'
        }
scat = ax.scatter([], [],
                c=df['group'].map(colors),
                )

def init():
    scat.set_offsets([])
    return scat,

def update(period):
    scat.set_offsets(df[df['period'] == period][['x', 'y']])
    scat.set_label(df[df['period']  == period]['group'])
    ax.legend([scat], df['group'].unique().tolist(), loc=1)
    ax.set_title(period)
    return scat,

ani = animation.FuncAnimation(fig, update, init_func=init,
                            frames=[1,2,3,4,5],
                            interval=500,
                            repeat=True)

plt.show()
6  a
7  b
8  c
Name: group, dtype:object
我在传奇中只看到a组

如果我只键入
ax.legend(loc=1)
,它会显示如下内容:

import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
colors = {
'a': 'r',
'b': 'b',
'c': 'g'
        }
scat = ax.scatter([], [],
                c=df['group'].map(colors),
                )

def init():
    scat.set_offsets([])
    return scat,

def update(period):
    scat.set_offsets(df[df['period'] == period][['x', 'y']])
    scat.set_label(df[df['period']  == period]['group'])
    ax.legend([scat], df['group'].unique().tolist(), loc=1)
    ax.set_title(period)
    return scat,

ani = animation.FuncAnimation(fig, update, init_func=init,
                            frames=[1,2,3,4,5],
                            interval=500,
                            repeat=True)

plt.show()
6  a
7  b
8  c
Name: group, dtype:object
数字在每一帧中都会变化

我已经检查了这些答案:
:让我回到现在的位置。
:我在
legend.remove()上获得
UnboundLocalError:赋值前引用的局部变量“legend”

:仅显示a组

我找到了解决办法。
我需要为每组创建一个散点图。然后我更新我的
update()
方法中的每个散点图。
这是我的最终代码:

fig, ax = plt.subplots()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
colors = {
    'a': 'r',
    'b': 'b',
    'c': 'g'
}

scats = []
groups = df.groupby('group')
for name, grp in groups:
    scat = ax.scatter([], [],
                      color=colors[name],
                      label=name)
    scats.append(scat)
ax.legend(loc=4)

def init():
    for scat in scats:
        scat.set_offsets([])
    return scats,

def update(period):
    for scat, (name, data) in zip(scats, groups):
        sample = data[data['period'] == period][['x', 'y']]
        scat.set_offsets(sample)
return scats,

ani = animation.FuncAnimation(fig, update, init_func=init
                              frames=[1, 2, 3, 4, 5],
                              interval=500,
                              repeat=True)

plt.show()