【发布时间】:2021-07-24 16:26:50
【问题描述】:
我有一个数据集,其中每一列是一个国家,每一行是一年,我想显示,以便以后建立条形图竞赛,每年排名前 5 的国家以及它们如何随时间变化。
为了做到这一点,我希望每个国家/地区每年都有相同的条形颜色,即使它们在年份之间改变位置。这就是为什么我对数据进行排名并将它们的排名用于 y 位置,而不是对其进行排序。
当我运行以下代码时,前 3 个条形图(1996 年到 1998 年)中的国家颜色是一致的,即使其中一个改变了位置,但从 1999 年到 2001 年,每个国家/地区都会改变颜色,直到 2001 年保持一致。
# Plotting several time periods, with ranking
dates = [1996, 1997, 1998, 1999, 2000, 2001]
# How many elements to show in each graph...
topN = 5
# Plot grid
fig, ax_array = plt.subplots(nrows = 1, ncols = 6, figsize = (10, 2.5), dpi = 144, tight_layout = True)
for ax, date in zip(ax_array, dates):
# Series with desired date
s = exp_data_wide.loc[date]
# Rank every country, then drop NaN values
s_rank = s.rank(method = 'first').dropna()
# X and Y values for the graphic
# Since I've got a large list of countries, and I must avoid sorting the data, I work with the last N values of the rank
y = s_rank[s_rank >= len(s_rank) - topN]
x = s[y.index]
ax.barh (y = y, width = x.values, color = colors, tick_label = x.index)
ax.set_title(date, fontsize = 'smaller')
prettify(ax)
例如,我不知道为什么法国条在前三年被绘制为粉红色,然后在 1999 年变为绿色,并在接下来的几年中保持不变。
我需要的是每年用相同的条形颜色绘制每个国家/地区。
你能帮我解决这个问题吗?
【问题讨论】:
标签: python dataframe matplotlib data-visualization bar-chart