how to make single stacked bar chart in ggplot2

前端 未结 2 1647
长发绾君心
长发绾君心 2020-12-16 04:03
Ancestry <- data.frame(Race = c(\"European\", \"African American\", \"Asian\", \"Hispanic\", \"Other\"), Proportion = c(40, 30, 10, 15, 5))
Ancestry %>% 
ggplo         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-16 04:51

    You need to create a dummy variable for x-axis. Then use geom_col which is similar to geom_bar(stat = "identity") to plot the stacked barplot + geom_text to put the text on the bar.

    The plot you showed used theme_economist from the ggthemes package.

    library(tidyverse)
    
    Ancestry <- data.frame(Race = c("European", "African American", "Asian", "Hispanic", "Other"), 
                           Proportion = c(40, 30, 10, 15, 5))
    
    Ancestry <- Ancestry %>% 
      mutate(Year = "2006")
    
    ggplot(Ancestry, aes(x = Year, y = Proportion, fill = Race)) +
      geom_col() +
      geom_text(aes(label = paste0(Proportion, "%")),
                position = position_stack(vjust = 0.5)) +
      scale_fill_brewer(palette = "Set2") +
      theme_minimal(base_size = 16) +
      ylab("Percentage") +
      xlab(NULL)
    

    library(ggthemes)
    
    ggplot(Ancestry, aes(x = Year, y = Proportion, fill = Race)) +
      geom_col() +
      geom_text(aes(label = paste0(Proportion, "%")),
                position = position_stack(vjust = 0.5)) +
      theme_economist(base_size = 14) +
      scale_fill_economist() +
      theme(legend.position = "right", 
            legend.title = element_blank()) +
      theme(axis.title.y = element_text(margin = margin(r = 20))) +
      ylab("Percentage") +
      xlab(NULL)
    

    Created on 2018-08-26 by the reprex package (v0.2.0.9000).

提交回复
热议问题