条形图中的类别颜色matplotlib

时间:2019-05-19 15:32:31

标签: pandas matplotlib

我想制作我的条形图,以便我的颜色与类别匹配,只是我要对数据框进行切片和分组以重新组织它。已经通过一些代码取得了一些结果。但是我的代码太怪异了,我想知道是否有某种方法可以使它更好。

pokecolor = {'Grass': '#78C850', 'Normal':'#A8A878','Fire':'#F08030','Fighting':'#C03028','Water':'#6890F0',           'Flying':'#A890F0','Poison':'#A040A0','Electric':'#F8D030','Ground':'#E0C068','Psychic':'#F85880','Rock':'#B8A038','Ice':'#98D8D8','Bug':'#A8B820','Dragon':'#7038F8','Ghost':'#705898','Dark':'#705848','Steel':'#B8B8D0','Fairy':'#EE99AC'}

df_poke['Type 1 color'] = df_poke['Type 1'].map(lambda x: pokecolor[x])

tipo1 = df_poke.loc[:,'Type 1'].value_counts(ascending=True)
tipo1.plot(kind='barh', grid=True, figsize=(15,8),
          xticks= [n for n in range(0,111, 10)],
          color=tipo1.reset_index()['index'].apply(lambda x : pokecolor[x]))

我不想不必使用“ tipo1”,重置其索引并对其应用pokecolor。

1 个答案:

答案 0 :(得分:0)

当您用Series绘制bar时,它将为每个条形使用不同的颜色。通过提供按.value_counts索引对齐的新列表来覆盖这些颜色:

样本数据

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(123)
df = pd.DataFrame({'Type 1': np.random.choice(list(pokecolor.keys()), 600)})

代码:

s = df['Type 1'].value_counts()
s.plot(kind='barh', figsize=(6,5), color=s.index.map(pokecolor)) 
plt.show()

输出:

enter image description here