2014-09-18 69 views
0

我使用seaborn Factorplot(kind = bar)來表示2個「類別」(每個類別3個條)中的總共6個小節。我想通過使用堆疊式設計來增強這個因子圖,也就是我想通過它的「子組件」來表示每個柱。 我知道這是可能的barplot,但是它也可能factorplot?在Seaborn Factorplot中使用「堆疊」設計

+0

顯示一些代碼,演示了數據的結構和whay你已經嘗試過。 – 2014-09-18 18:14:17

回答

1

Randy Zwitch explains如何在seaborn中創建堆疊條形圖。

解決的辦法是將疊加的條形圖視爲多個疊加在同一圖形上的圖表,以便條形圖的底部部分位於前部並且隱藏後續部分的最低部分。

從他的博客引用:

import pandas as pd 
from matplotlib import pyplot as plt 
import matplotlib as mpl 
import seaborn as sns 
%matplotlib inline 

#Read in data & create total column 
stacked_bar_data = pd.read_csv("C:\stacked_bar.csv") 
stacked_bar_data["total"] = stacked_bar_data.Series1 + stacked_bar_data.Series2 

#Set general plot properties 
sns.set_style("white") 
sns.set_context({"figure.figsize": (24, 10)}) 

#Plot 1 - background - "total" (top) series 
sns.barplot(x = stacked_bar_data.Group, y = stacked_bar_data.total, color = "red") 

#Plot 2 - overlay - "bottom" series 
bottom_plot = sns.barplot(x = stacked_bar_data.Group, y = stacked_bar_data.Series1, color = "#0000A3") 


topbar = plt.Rectangle((0,0),1,1,fc="red", edgecolor = 'none') 
bottombar = plt.Rectangle((0,0),1,1,fc='#0000A3', edgecolor = 'none') 
l = plt.legend([bottombar, topbar], ['Bottom Bar', 'Top Bar'], loc=1, ncol = 2, prop={'size':16}) 
l.draw_frame(False) 

#Optional code - Make plot look nicer 
sns.despine(left=True) 
bottom_plot.set_ylabel("Y-axis label") 
bottom_plot.set_xlabel("X-axis label") 

#Set fonts to consistent 16pt size 
for item in ([bottom_plot.xaxis.label, bottom_plot.yaxis.label] + 
      bottom_plot.get_xticklabels() + bottom_plot.get_yticklabels()): 
    item.set_fontsize(16)