Kristen Cyr
Kristen Cyr

Reputation: 726

How do I connect my points with lines, but by different groups in gpplot?

I'm trying to make graph where my points are connected with a line. The problem I'm having is that my points under the same column are associated with different values so when I add the geom_line it goes through all groups as 1 line. How can I separate the line so that it only connects the points with the same variables?

here is some sample code

temps = data.frame(Temperature= c(15,25,35), 
                                    Growth.Phase = c("exponential", "stationary", "death"),
                                    Carbohydrates = sample(c(3:10), 9, replace = T))

temps$Shape = if_else(temps$Growth.Phase == "exponential", 21,
                      if_else(temps$Growth.Phase == "stationary", 22, 23))

I want 3 lines, each line connecting the dots with the same symbols but when I use ```geom_line`` for example....

ggplot(data = temps, aes(x = Temperature, y = "Proportions")) +
  geom_point(aes(y = Carbohydrates),colour = "darkred", 
             fill = "darkred", shape = temps$Shape, size = 3) +
  geom_line(aes(y = Carbohydrates))

I get this image

enter image description here

Does anyone know how to fix this?

Upvotes: 1

Views: 50

Answers (1)

astrofunkswag
astrofunkswag

Reputation: 2698

You can put shape inside the first aesthetics, then it gets used in the geom_line as a grouping variable

ggplot(data = temps, aes(x = Temperature, y = "Proportions", shape = factor(Shape))) +
  geom_point(aes(y = Carbohydrates),colour = "darkred", 
             fill = "darkred", size = 3) +
  geom_line(aes(y = Carbohydrates))

enter image description here

If the points are not in the right order when the lines aren't vertical, you can use temps %>% dplyr::arrange(Carbohydrates)

Upvotes: 1

Related Questions