我正在尝试创建一个堆积条形图,以显示卫星运载火箭随时间的变化情况。我希望x轴是发射的年份,y轴是在车辆上发射的卫星的数量,其中杆的每个部分是代表运载火箭的不同颜色。我正在努力想出办法,因为我的运载火箭列是非数字的。我按功能和value_counts调查了这个组,但似乎无法让它做我正在寻找的东西。
答案 0 :(得分: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()
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