Is it possible to add one bar plot with another

Hi,
I want to creat a bar chart showing the pay mix (base pay+variable pay) in a company vs external market.
I have created a data frame as below.

country pay.type BS market
1 France base 40000 40000
2 Belgium base 45000 37000
3 Spain base 36000 36000
4 France var 7000 8000
5 Belgium var 12000 12000
6 Spain var 8000 7200

Below is my R script which does work? Is there a way to put market pay mix and BS pay mix in the same bar chart?

P<- ggplot(pay.mix.test, aes(x=country,y=BS, fill=pay.type))+geom_bar(position="stack",stat="identity")
P+ggplot(pay.mix.test, aes(x=country,y=market, fill=pay.type))+geom_bar(position="stack",stat="identity")
Error: Can't add ggplot(pay.mix.test, aes(x = country, y = market, fill = pay.type)) to a ggplot object.

You do not need to call ggplot() twice to add a second geom. I have modified your code so it can run but I have also showed how to reshape the data to have more options for plotting.
Notice how I used the data.frame() function to construct the data. This makes it easy for others to copy the code and run it.

library(ggplot2)
pay.mix.test <- data.frame(country = c("F", "B", "S", "F", "B", "S"),
                           pay.type = c("base", "base", "base", "var", "var", "var"),
                           BS = c(40, 45, 36,70,12,8),
                           market =  c(40, 37, 36, 8, 12, 7.2))

#Minimal code changes to avoid the error
P <- ggplot(pay.mix.test, aes(x=country,y=BS, fill=pay.type)) + 
  geom_bar(position="stack",stat="identity")
P + geom_bar(aes(y=market, fill=pay.type), 
            position="stack",stat="identity")


#Reshape the data.
library(tidyr)
TallDF <- pivot_longer(pay.mix.test, BS:market, names_to = "pay_group", 
                       values_to = "Value")
TallDF
#> # A tibble: 12 x 4
#>    country pay.type pay_group Value
#>    <fct>   <fct>    <chr>     <dbl>
#>  1 F       base     BS         40  
#>  2 F       base     market     40  
#>  3 B       base     BS         45  
#>  4 B       base     market     37  
#>  5 S       base     BS         36  
#>  6 S       base     market     36  
#>  7 F       var      BS         70  
#>  8 F       var      market      8  
#>  9 B       var      BS         12  
#> 10 B       var      market     12  
#> 11 S       var      BS          8  
#> 12 S       var      market      7.2
ggplot(TallDF, aes(x = country, y = Value, fill = pay.type)) + geom_col() +
  facet_wrap(~ pay_group, nrow = 1)

Created on 2020-05-30 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.