【问题标题】:Creating a stacked bar chart (using data from 2 columns)创建堆积条形图(使用 2 列中的数据)
【发布时间】:2022-11-03 02:09:14
【问题描述】:

我正在尝试创建堆叠条形图但无法创建“堆叠部分”。我希望将我的条形高度作为 gdp_per_capita 列,然后我希望将 gdp_per_capita_agg_percen 列显示为每列的一部分(这是我的 gdp_per_capita 列的百分比)。为了更清楚地了解国家 1,我需要列值为 3281,然后其中的堆栈部分为 676(占其中的 20.6%)。

下面使用的数据和代码;

数据

 df2
   Country_Name            gdp_per_capita     `Agriculture_GDP%`  gdp_per_capita_agg_percen
 1 Albania                         3281               20.6                      676
 2 Algeria                         3515               9.86                      346
 3 Bosnia and Herzegovina          3828               8.21                      314
 4 Croatia                        11285               3.90                      440
 5 Cyprus                         24686               2.60                      643
 6 Egypt, Arab Rep.                2192               13.3                      292 

当前没有堆栈的代码; 我阅读了有关在 geom_bar 参数中使用 position="stack" 的信息,但不确定如何为堆栈添加我的 gdp_per_capita_agg_percen 数据

ggplot(df2, aes(x = as.factor(Country_Name), y = gdp_per_capita, fill = as.factor(Country_Name))) +
geom_bar(stat = "identity")       

【问题讨论】:

    标签: r


    【解决方案1】:

    不会称之为堆叠。但是您可以通过第二个geom_col/bar 达到您想要的结果:

    library(ggplot2)
    
    ggplot(df2, aes(x = as.factor(Country_Name), y = gdp_per_capita, fill = "GDP")) +
      geom_col() +
      geom_col(aes(y = gdp_per_capita_agg_percen, fill = "Agriculture"))   
    

    数据

    structure(list(Country_Name = c("Albania", "Algeria", "Bosnia and Herzegovina", 
    "Croatia", "Cyprus", "Egypt, Arab Rep."), gdp_per_capita = c(3281L, 
    3515L, 3828L, 11285L, 24686L, 2192L), `Agriculture_GDP%` = c(20.6, 
    9.86, 8.21, 3.9, 2.6, 13.3), gdp_per_capita_agg_percen = c(676L, 
    346L, 314L, 440L, 643L, 292L)), class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5", "6"))
    

    【讨论】:

    • 是的,您是对的,因为它是整体价值中的一个价值。不确定我们会在这里叫它什么,但这就是我正在寻找的输出
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 2021-09-22
    相关资源
    最近更新 更多