Stuck
Stuck

Reputation: 75

how to plot two sets of data onto one set of axis whilst still having a facet wrap in ggplot2 for R?

Struggling with producing two sets of data from one data frame splitting it by a variable sex.
The variable sex is either Male or Female.

ggplot(student_data, 
       aes(x = height, 
           y = age, 
           group = eye_colour, colour = sex)) +
  geom_line(lwd = 1.5) + 
  facet_wrap(~ eye_colour, scales = "free_y") + 
  theme(axis.text.x = element_text(size = 14, angle = 270, hjust = 0, vjust = 0.5), 
        axis.text.y = element_text(size = 14), 
        axis.title.x = element_text(size = 16),
        axis.title.y = element_text(size = 16, angle = 270),
        strip.text.x = element_text(size = 14),
        title = element_text(size = 20), 
        legend.position = "none") + 

Currently this outputs one line with both data that alternates colour between each point. However, I cant seem to get it to formulate two lines even though its able to differentiate between the variable.

Many thanks in advance,
Samuel

Upvotes: 1

Views: 76

Answers (1)

Amar
Amar

Reputation: 1373

group should be sex. colour should be eye_colour. Next time provide a minimal reproducible example such as the one below.

library(ggplot2)
student_data <- data.frame(age = c(5,22,33,4,45), height = c(25,39,5,6,2), 
                           eye_colour = c("red", "green", "brown", "brown", "brown"),
                           sex = c("f", "m", "m", "f", "m"))

ggplot(student_data, aes(x = height, y = age, group = sex, colour = sex)) +
geom_line()

Upvotes: 2

Related Questions