2017-04-20 89 views
0
import matplotlib.pyplot as plt 
import seaborn as sns 

rankings_by_age = star_wars.groupby("Age").agg(np.mean).iloc[:,8:] 

age_first = rankings_by_age.iloc[0, :].values 
age_second = rankings_by_age.iloc[1, :].values 
age_third = rankings_by_age.iloc[2, :].values 
age_fourth = rankings_by_age.iloc[3, :].values 

fig, ax = plt.subplots(figsize=(12, 9)) 

ind = np.arange(6) 
width = 0.2 

rects_1 = ax.bar(ind, age_first, width, color=(114/255,158/255,206/255), 
alpha=.8) 
rects_2 = ax.bar(ind+width, age_second, width, color= 
(255/255,158/255,74/255), alpha=.8) 
rects_3 = ax.bar(ind+2*width, age_third, width, color= 
(103/255,191/255,92/255), alpha=.8) 
rects_4 = ax.bar(ind+3*width, age_fourth, width, color= 
(237/255,102/255,93/255), alpha=.8) 

ax.set_title("Star Wars Film Rankings by Age") 
ax.set_ylabel("Ranking") 
ax.set_xticks(ind) 
ax.set_xticklabels(titles, rotation=45) 

ax.tick_params(top='off', right='off', left='off', bottom='off') 
ax.spines['top'].set_visible(False) 
ax.spines['right'].set_visible(False) 

ax.legend((rects_1[0], rects_2[0], rects_3[0], rects_4[0]), ('18-29', '30- 
44', '45-60', '> 60'), title="Age") 

plt.show() 

enter image description here如何使用seaborn繪製此圖?

我想複製使用seaborn這個情節,但我不知道如何去爲每個類別繪製多條。我瞭解如何一次使用一個年齡組,但每個年齡段獲得多個酒吧似乎都很棘手。任何幫助,將不勝感激。

+1

你會得到更好的反應,如果你(1)顯示您的最佳的工作Seaborn碼,和(2)顯示在做多吧你最好的嘗試失敗。這可以將修正減少到一兩行。 – Prune

+1

這個問題還不清楚。問題中的代碼(除了不可重現,請參閱[mcve])已經給出了預期的結果。那麼在這裏「使用海豹」究竟意味着什麼? – ImportanceOfBeingErnest

+1

這些排名也很糟糕! – mwaskom

回答

1

通過引用seaborn bar plot documentation,您可以使用hue參數來確定條應該按哪個數據幀列分組。

import seaborn.apionly as sns 
import matplotlib.pyplot as plt 

df = sns.load_dataset("tips") 
ax = sns.barplot(data=df, x="day", y="total_bill", hue="sex") 

plt.show() 

enter image description here

+0

嗨,對不起,不好意思。我明白'色調'參數,但我想知道是否可以每天繪製多列。例如,如果我想每天繪製'total_bill'和'total_tip'(因爲它們共享相同的單位,所以可以使用相同的y軸)。所以,在'hue'參數設置爲'sex'的情況下,上例中每天的酒吧總數爲4。 – apkim221

+0

如果你想使用'sns.barplot'函數,你需要重新組織數據,以便有一個列中包含相應的功能。這是seaborn的缺點;它只適用於漂亮的標準數據格式。 – ImportanceOfBeingErnest