Layman Tucker
Layman Tucker

Reputation: 39

Plotting stacked bar chart in ggplot2: presenting a variable as percentage of another variable

As the title states, I am trying to plot a stacked bar chart where one stack is supposed to make up a percentage of the other stack, not a combined percentage.

The application is sampling, and I want to show the sample size as a percentage of the population size.

This is what I have tried: The table on the left is plotted into the bar chart on the right.

enter image description here

See below for the code:

temp <- Countemf()
temp$Type <- factor(temp$Type)

temp %>% 
  rename(Environment=Type)%>% 
  tidyr::gather(Class, Size, -Environment ) %>% 
  ggplot(., aes(x=Environment, y=Size, fill=Class)) +
    geom_bar(stat="identity",position = "fill")+  
    scale_y_continuous(labels = scales::percent_format())

Upvotes: 0

Views: 72

Answers (1)

sambold
sambold

Reputation: 817

I am still not sure, if I understood you correctly. But I decided it is easier to clarify things with an example. So here is a possible (but probably not the most elegant) solution to your problem:

temp <- dplyr::tibble(type=c("Core","Mainframe","Network","Oracle","Unix"),
                      sample=c(2,2,3,2,2),
                      pop=c(4,17,31,3,2))
temp %>%
    dplyr::mutate(diff=pop-sample) %>%
    tidyr::pivot_longer(cols=c(sample,pop,diff)) %>%
    dplyr::filter(name!="pop") %>%
    ggplot2::ggplot(ggplot2::aes(x=type,y=value,fill=name)) +
    ggplot2::geom_bar(stat="identity") 

Upvotes: 2

Related Questions