1

考虑一个具有多列的 Pandas 数据框,每列一个国家名称,多行,每行一个日期。这些单元格是有关国家/地区的数据,这些数据会随时间变化。这是 CSV:

https://pastebin.com/bJbDz7ei

我想在 Jupyter 中制作一个动态图(动画),显示数据如何随时间演变。在世界上所有国家中,我只想展示在任何给定时间排名前 10 的国家。因此图中显示的国家/地区可能会不时发生变化(因为前 10 名正在演变)。

我还想在颜色方面保持一致性。任何时候只显示10个国家,有些国家几乎连续出现和消失,但任何国家的颜色在整个动画中都不应该改变。任何国家的颜色都应该从头到尾坚持下去。

这是我拥有的代码(编辑:现在您可以将代码复制/粘贴到 Jupyter 中,它开箱即用,因此您可以轻松看到我正在谈论的错误):

import pandas as pd
import requests
import os
from matplotlib import pyplot as plt
import matplotlib.animation as ani

rel_big_file = 'rel_big.csv'
rel_big_url = 'https://pastebin.com/raw/bJbDz7ei'

if not os.path.exists(rel_big_file):
    r = requests.get(rel_big_url)
    with open(rel_big_file, 'wb') as f:
        f.write(r.content)

rel_big = pd.read_csv(rel_big_file, index_col='Date')

# history of top N countries
champs = []
# frame draw function
def animate_graph(i=int):
    N = 10
    # get current values for each country
    last_index = rel_big.index[i]
    # which countries are top N in last_index?
    topN = rel_big.loc[last_index].sort_values(ascending=False).head(N).index.tolist()
    # if country not already in champs, add it
    for c in topN:
        if c not in champs:
            champs.append(c)
    # pull a standard color map from matplotlib
    cmap = plt.get_cmap("tab20")
    # draw legend
    plt.legend(topN)
    # make a temporary dataframe with only top N countries
    rel_plot = rel_big[topN].copy(deep=True)
    # plot temporary dataframe
    p = plt.plot(rel_plot[:i].index, rel_plot[:i].values)
    # set color for each country based on index in champs
    for i in range(0, N):
        p[i].set_color(cmap(champs.index(topN[i]) % 20))

%matplotlib notebook
fig = plt.figure(figsize=(10, 6))
plt.xticks(rotation=45, ha="right", rotation_mode="anchor")
# x ticks get too crowded, limit their number
plt.gca().xaxis.set_major_locator(plt.MaxNLocator(nbins=10))
animator = ani.FuncAnimation(fig, animate_graph, interval = 333)
plt.show()

它完成了这项工作 - 有点。我将排名靠前的国家存储在冠军列表中,并根据每个国家在冠军中的索引分配颜色。但是根据 champs 中的索引,仅正确分配了绘制线的颜色。

传说中的颜色是固定分配的,传说中的第一个国家总是得到相同的颜色,传说中的第二个国家总是得到某种颜色,等等,基本上每个国家的颜色在整个动画中都是不同的当国家在传说中上下移动时。

绘制线条的颜色遵循 champs 中的索引。图例中国家的颜色基于图例中的顺序。这不是我想要的。

如何以与情节线相匹配的方式为图例中的每个国家/地区分配颜色?

4

2 回答 2

1

在此处输入图像描述这是我的解决方案:

我删除了您生成颜色的代码并设置了一个新的工作代码:

首先,我在字典中用自己独特的颜色初始化了每个国家:

# initializing fixed color to all countries
colorsCountries = {}
for country in rel_big.columns:
    colorsCountries[country] = random.choice(list(mcd.CSS4_COLORS.keys()))

然后我替换了这个:

# plot temporary dataframe
p = plt.plot(rel_plot[:i].index, rel_plot[:i].values)

有了这个 :

# plot temporary dataframe
for keyIndex in rel_plot[:i].keys() :
    p = plt.plot(rel_plot[:i].index,rel_plot[:i][keyIndex].values,color=colorsCountries[keyIndex])

然后添加了更新matplotlib图例标签和颜色的代码

leg = plt.legend(topN)
for line, text in zip(leg.get_lines(), leg.get_texts()):
    line.set_color(colorsCountries[text.get_text()])

不要忘记添加导入:

import matplotlib._color_data as mcd
import random

这是完整的建议解决方案:

import pandas as pd
import requests
import os
from matplotlib import pyplot as plt
import matplotlib.animation as ani
import matplotlib._color_data as mcd
import random

rel_big_file = 'rel_big.csv'
rel_big_url = 'https://pastebin.com/raw/bJbDz7ei'

if not os.path.exists(rel_big_file):
    r = requests.get(rel_big_url)
    with open(rel_big_file, 'wb') as f:
        f.write(r.content)

rel_big = pd.read_csv(rel_big_file, index_col='Date')

# history of top N countries
champs = []
# initializing fixed color to all countries
colorsCountries = {}
for country in rel_big.columns:
    colorsCountries[country] = random.choice(list(mcd.CSS4_COLORS.keys()))
# frame draw function
def animate_graph(i=int):
    N = 10
    # get current values for each country
    last_index = rel_big.index[i]
    # which countries are top N in last_index?
    topN = rel_big.loc[last_index].sort_values(ascending=False).head(N).index.tolist()
    # if country not already in champs, add it
    for c in topN:
        if c not in champs:
            champs.append(c)
    # pull a standard color map from matplotlib
    cmap = plt.get_cmap("tab20")
    # draw legend
    plt.legend(topN)
    # make a temporary dataframe with only top N countries
    rel_plot = rel_big[topN].copy(deep=True)
    # plot temporary dataframe
    #### Removed Code
    #p = plt.plot(rel_plot[:i].index, rel_plot[:i].values)
    #### Removed Code
    for keyIndex in rel_plot[:i].keys() :
        p = plt.plot(rel_plot[:i].index,rel_plot[:i][keyIndex].values,color=colorsCountries[keyIndex])
    # set color for each country based on index in champs
    #### Removed Code
    #for i in range(0, N):
        #p[i].set_color(cmap(champs.index(topN[i]) % 20))
    #### Removed Code
    leg = plt.legend(topN)
    for line, text in zip(leg.get_lines(), leg.get_texts()):
        line.set_color(colorsCountries[text.get_text()])

%matplotlib notebook
fig = plt.figure(figsize=(10, 6))
plt.xticks(rotation=45, ha="right", rotation_mode="anchor")
# x ticks get too crowded, limit their number
plt.gca().xaxis.set_major_locator(plt.MaxNLocator(nbins=10))
animator = ani.FuncAnimation(fig, animate_graph, interval = 333)
plt.show()
于 2020-05-14T15:07:28.027 回答
1

ZINE Mahmoud 的回答很棒。我只改变了一件事——我希望每次运行时都能确定性地分配颜色,所以我没有使用随机方法将颜色分配给这样的国家:

colorsCountries = {}
colorPalette = list(mcd.CSS4_COLORS.keys())
for country in rel_big.columns:
    colorsCountries[country] = colorPalette[rel_big.columns.tolist().index(country) % len(colorPalette)]
于 2020-05-18T04:27:26.730 回答