user7729135
user7729135

Reputation: 409

Barplot overlay with geom line

here is the data example:

S   P   C   P_int C_int
10  20  164 72    64 
20  550 709 92    89 
30  142 192 97    96 
40  45  61  99    98 
50  12  20  99    99 
60  5   6   99    99 
70  2   2   99    99 
80  4   1   99    99 
90  1   0   10    99 
100 0   1   10    99

Let's say i have a dataframe called df, the aim is to have a bar chart using variables P and C, with an line chart overlayed using sum of variables P_int and C_int. Currently I have these lines of codes to create the bar chart:

final <- df %>% tidyr::gather(type, value, c(`P`, `C`))
ggplot(final, aes(S))+
  geom_bar(aes(y=value, fill=type), stat="identity", position="dodge")

The thing I can't figure out is hot to plot the sum of variables P_int and C_int as a line chart overlayed on the above plot with a second Y axis. Would appreciate any help.

Upvotes: 1

Views: 459

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

Do you need something like this ?

library(ggplot2)
library(dplyr)

ggplot(final, aes(S))+
  geom_bar(aes(y=value, fill=type), stat="identity", position="dodge") + 
  geom_line(data = final %>% 
                    group_by(S) %>% 
                    summarise(total = sum(P_int + C_int)), 
            aes(y = total), color = 'blue') +
  scale_y_continuous(sec.axis = sec_axis(~./1)) +
  theme_classic()

enter image description here

I have kept the scale of secondary y-axis same as primary y-axis since they are in the same range but you might need to adjust it in according to your real data.

Upvotes: 3

Related Questions