首页 文章

将二进制变量绘制为百分比

提问于
浏览
1

我有一个包含两个变量的数据集:1)国家; 2)联合政府或不随着时间的推移(二进制) .

我想用ggplot绘制一个条形图,其中我在X轴上有国家,以及该国有联合政府的年数百分比(Y = 1) . 每个国家应该总和100 pct . 导致它们具有相同的大小 .

这个问题(Create stacked barplot where each stack is scaled to sum to 100%)基本上是相同的情节,除了我只有两个结果(联合政府与否),而不是五个 .

虽然我按照问题的答案中的说明进行操作,但是我使用以下代码获得了附加的不成功的情节:

ggplot(data,aes(x = countryname, y = alliance,fill = alliance)) + 
  geom_bar(position = "fill",stat = "identity") + 
  scale_y_discrete(labels = percent_format())

我不知道我做错了什么,现在我尝试了很多不同的事情 . 谁能帮我?

enter image description here

1 回答

  • 2

    我会尝试通过生成一些随机数据来回答您的描述 . 希望您可以根据自己的需要重新设计此示例 .

    # Sample data set
    year <- 1990:2016
    
    n <- length(year)
    country <- rep(c("US", "Canada", "England", "France", "Germany"), each = n)
    govt <- sample(c(1, 0), size = length(country), replace = T)
    
    df <- data.frame(country, year = rep(year, times = 5), govt)
    head(df)
    
    # Create summary
    library(ggplot2)
    library(dplyr)
    library(reshape2)
    
    df.plot <- df %>% 
      group_by(country) %>% 
      summarize(coalition = sum(govt)/n(),
                non.coalition = 1-coalition)
    
    # Check
    rowSums(df.plot[,-1])
    
    # Now plot
    df.plot %>% 
      melt() %>% 
      ggplot(aes(x = country, y = value, fill = variable)) + geom_bar(stat = "identity", position = "stack") + 
      xlab("Country") + 
      ylab("Percent Coalition / Non Coalition") +
      scale_fill_discrete(guide = guide_legend(title = "Type of Govt."))
    

相关问题