Home > Mobile >  Connect points with a line
Connect points with a line

Time:06-02

The data looks like this

score<-c(3.2,3.5,5.4,5.5)
subject<-c('math','math','reading','reading')
sex<-c('men','women')

data<-data.frame(sex,score,subject)

data %>% 
  ggplot(aes(x=score,y=subject,color=sex))  
  geom_point()

I would like to connect the dots (between the subjects from men to women) to show gender gap. This doesn't seem to be possible by just adding geom_line().

CodePudding user response:

The following code (from yours above) generates the same plot, but now the points are linked between sex for each subject.

data %>% 
  ggplot(aes(x=score,y=subject))  
  geom_line() 
  geom_point(aes(color=sex))

plot

Notice that color=sex must be defined just for geom_point() instead of for the general ggplot fun.

CodePudding user response:

You can just use group like mentioned in the comments:

library(tidyverse)
data %>% 
  ggplot(aes(x=score,y=subject,color=sex, group = subject))  
  geom_point()  
  geom_line(col = "black")

Output:

enter image description here

  • Related