Home > database >  overlay a line graph and a point graph into a stacked bar graph with two different axis
overlay a line graph and a point graph into a stacked bar graph with two different axis

Time:10-19

Here is my data

data <- data.frame(question=c("A1","A2","A3","A4","A5","A1","A2","A3","A4","A5","A1","A2","A3","A4","A5"),
                   response=c("yes", "yes", "yes", "no", "no", "maybe", "maybe","no", "yes", "no","maybe", "yes", "yes", "no", "maybe"),
                   question_mean = c(3.4,4.5,3,3.4,5,3.4,4.5,3,3.4,5,3.4,4.5,3,3.4,5),
                   domain_mean = c(4,4,4,4,4,4,4,4,4,4,4,4,4,4,4))

data$sum <- 1

data <- data %>%
  group_by(question, response,question_mean,domain_mean ) %>%
  dplyr::summarise(sum = sum(sum))




I would like to create a stacked percent bargraph and then overlay a linegraph and a point graph onto the bargraph. This is my code for each individual graph

#bargraph
ggplot(data)  
  geom_bar(aes(x=question, y=sum,  fill=response),stat="identity", position = "fill")

#Line graph
ggplot(data)  
  geom_line(aes(x=question, y=domain_mean),stat="identity", group = 1) 

#point graph
ggplot(data)  
 geom_point(aes(x=question, y=question_mean))

Here is my attempt to overlay all of them together; but I cant seem to figure out the axis. I would like the left hand to be 0-100 (percent for the bargraph) and then the right hand axis to be for the mean score (for the line and point graph).

ratio <- max(data$question_mean)

ggplot(data)  
  geom_bar(aes(x=question, y=sum,  fill=response),stat="identity", position = "fill")  
  geom_line(aes(x=question, y=domain_mean),stat="identity", group = 1)  
 geom_point(aes(x=question, y=question_mean))  
  scale_y_continuous("Response %", sec.axis = sec_axis(~ . / ratio, name = "Mean Score"))


enter image description here

This is what I am hoping to get:

enter image description here

Any help is appreciated - thanks so much!

CodePudding user response:

Several things:

  • your ratio is apparently 6, not 5 (given your expected output)
  • you need to divide every y values in by the ratio in the aesthetic, and multiply it in the sec_axis call (since you want a scale from 0 to 6).
  • you can use lty for geom_line and shape for geom_point to force them to be added in the legend.
ratio <- 6
ggplot(data)  
  aes(x = question)  
  geom_col(aes(y = sum, fill = response), position = "fill")  
  geom_line(aes(y = domain_mean / ratio, group = 1, lty = "Mean"), size = 2)  
  geom_point(aes(y = question_mean / ratio, shape = "Question means"), 
             colour = "darkgreen", size = 3)  
  scale_y_continuous("Response %", label = scales::label_percent(),
                     sec.axis = sec_axis(~ . * ratio, name = "Mean Score"))  
  scale_fill_manual(values = c("grey", "orange2", "darkblue"))  
  theme_minimal()  
  theme(legend.title = element_blank())

enter image description here

  • Related