2017-04-16 47 views
1

我正在嘗試創建堆積條形圖以顯示隨着時間的推移,衛星的運載工具如何變化。我希望x軸是發射年份,y軸是車輛上發射的衛星的數量,其中每個小節的部分是代表運載火箭的不同顏色。我很難想出辦法做到這一點,因爲我的運載火箭專欄是非數字的。我通過函數和value_counts調查了這個組,但似乎無法讓它做我正在尋找的東西。堆積條形圖 - 從非數字項目開始

enter image description here

+0

您應該提供的代碼哪個人可以複製你的數據框。無論如何,答案應該是'pd.DataFrame(df.groupby(['Launch','Launch Vehicle'))。agg({'Launch Vehicle':'count'})。reset_index())'。這將爲您提供創建繪圖所需的分組數據框。 – vagabond

回答

1

你必須重新整理數據所需的方式使用DataFrame.plot

import pandas as pd 
import matplotlib.pylab as plt 

# test data 
df = pd.DataFrame({'Launch Vehicle':["Soyuz 2.1a",'Ariane 5 ECA','Falcon 9','Long March','Falcon 9', 'Atlas 3','Atlas 3'], 
'Year of Launch': [2016,2014,2016,1997,2015,2004,2004]}) 

# make groupby by year and rocket type to get the pivot table 
# fillna put zero launch if there is no start of such type during the year 
df2 = df.groupby(['Year of Launch','Launch Vehicle'])['Year of Launch'].count().unstack('Launch Vehicle').fillna(0) 
print(df2) 

# plot the data 
df2.plot(kind='bar', stacked=True, rot=1) 
plt.show() 

enter image description here

DF2的輸出:

Launch Vehicle Ariane 5 ECA Atlas 3 Falcon 9 Long March Soyuz 2.1a 
Year of Launch               
1997      0.0  0.0  0.0   1.0   0.0 
2004      0.0  2.0  0.0   0.0   0.0 
2014      1.0  0.0  0.0   0.0   0.0 
2015      0.0  0.0  1.0   0.0   0.0 
2016      0.0  0.0  1.0   0.0   1.0