Plotting variables in a dataframe with different colours for each category

I will try to keep it simple.

I have a mock dataset in R, for a certain group of people. There are four columns: 'Name,' 'Sex,' 'Height,' Weight'.

The Name is essentially just a categorical variable: 'A1, A2, A3...' and can be conveniently ignored.
Sex is either 'M' or 'F'.

I need to make a scatterplot of 'Height' and 'Weight,' but where the points for both males and females are displayed with a different symbol or colour. Can you please help me out?

I am using
plot(Weight ~ Height, data = Students, col = "blue", xlim = c(min(Height), max(Height)), ylim=c(0, 100)).

It generates a graph alright, but I cannot see Males and Females in a different colour (the cells for 'Sex' mention M or F for males or females respectively).

Using ggplot you can do the following (here using mock data that is not entirely realistic, but it shows the point):


mf <- tibble(
  name =  paste0("A", rep(1:10)),
  sex = rep(c("M", "F"), 5), 
  height = rnorm(10, mean = 160, sd = 15), 
  weight = rnorm(10, mean = 75, sd = 10)

mf %>% 
  ggplot(aes(height, weight)) +
  geom_point(aes(color = sex))

Created on 2021-10-15 by the reprex package (v2.0.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.