Search code examples
rggplot2scatter-plot

Geom_line connects geom points based on y-axis?


I'm trying to connect the points of a ggplot based on position in the x-axis, but using the base settings my plot connects points based on their y-axis lines: base ggplot

When I add group=1 to geom_line() it connects the points by the y-axis:

geom_line(group=1)

Here's a copy of the code and a small SRS. I just want my points to be connected by the order they appear on the x-axis, thanks in advance.

df
#      x z   y
#  1:  1 A A27
#  2:  2 C C11
#  3:  3 A A19
#  4:  4 A A27
#  5:  5 B B25
#  6:  6 A A27
#  7:  7 B B25
#  8:  8 B B26
#  9:  9 A A29
# 10: 10 A A38
ggplot(df, aes(x, y, color=z))+geom_point(size=3) +geom_line(size =1, group=1)+
  scale_y_discrete(limits=rev)

Solution

  • Are you looking for such a solution? Put the group=1 in the aesthetics.

    ggplot(df, aes(x, y, color=z, group=1))+geom_point(size=3) +geom_line(size =1)+
      scale_y_discrete(limits=rev)
    

    enter image description here