大Pandas复杂堆积呕吐物

2024-05-14 09:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据:

    Year    LandUse     Region  Area
0   2005    Corn        LP  2078875
1   2005    Corn        UP  149102.4
2   2005    Open Lands      LP  271715
3   2005    Open Lands      UP  232290.1
4   2005    Soybeans        LP  1791342
5   2005    Soybeans        UP  50799.12
6   2005    Other Ag        LP  638010.4
7   2005    Other Ag        UP  125527.2
8   2005    Forests/Wetlands        LP  69629.86
9   2005    Forests/Wetlands        UP  26511.43
10  2005    Developed       LP  10225.56
11  2005    Developed       UP  1248.442
12  2010    Corn        LP  2303999
13  2010    Corn        UP  201977.2
14  2010    Open Lands      LP  131696.3
15  2010    Open Lands      UP  45845.81
16  2010    Soybeans        LP  1811186
17  2010    Soybeans        UP  66271.21
18  2010    Other Ag        LP  635332.9
19  2010    Other Ag        UP  257439.9
20  2010    Forests/Wetlands        LP  48124.43
21  2010    Forests/Wetlands        UP  23433.76
22  2010    Developed       LP  7619.853
23  2010    Developed       UP  707.4816

如何使用pandas绘制一个堆叠条形图,在y轴上显示面积,并使用“REGION”构建堆叠,在x轴上使用年份和土地利用。你知道吗


Tags: 数据openyearregionotherlpupag
1条回答
网友
1楼 · 发布于 2024-05-14 09:19:37

熊猫图的主要内容是找出熊猫期望数据的形状。如果我们重新调整,使年份在索引中,不同的地区在不同的列中:

# Assuming that we want to sum the areas for different
# LandUse's within each region
plot_table = df.pivot_table(index='Year', columns='Region', 
                            values='Area', aggfunc='sum')
plot_table

Out[39]: 
Region           LP           UP
Year                            
2005    4859797.820  585478.6920
2010    4937958.483  595675.3616

情节很直接:

plot_table.plot(kind='bar', stacked=True)

在x轴上既有年份又有土地利用,不需要太多额外的工作,你可以 在创建用于打印的表时,将两者都放入索引中:

plot_table = df.pivot_table(index=['Year', 'LandUse'], 
                            columns='Region', 
                            values='Area', aggfunc='sum')

enter image description here

相关问题 更多 >

    热门问题