0

I'm trying to plot lines for men and women against their year of birth (labelled birthy) on the same graph, using the dataframe below

 df  <- data.frame(birthy=c("1881-1890","1960-1962","2016-2018"),
              Men=c(76.1, 77.5, 84.9),
              Women=c(77.3, 80.7, 87.6))

I tried the following code in ggplot2

ggplot(df, aes(birthy)) + 
geom_line(aes(y = Men, colour = "Men")) + 
geom_line(aes(y = Women, colour = "Women"))

and R throws the following error

geom_path: Each group consists of only one observation. Do you need to adjust
the group aesthetic?

I'm looking for a way to fix this error. Any help is well appreciated!

T Richard
  • 525
  • 2
  • 9

2 Answers2

3

Try this:

#Code
ggplot(df, aes(birthy)) + 
  geom_line(aes(y = Men, colour = "Men",group=1)) + 
  geom_line(aes(y = Women, colour = "Women",group=1))

Output:

enter image description here

Or better reshaping your data to long:

library(tidyverse)
#Code 2
df %>% pivot_longer(-1) %>%
  ggplot(aes(x=birthy,y=value,color=name,group=name))+
  geom_line()

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84
0

I know this dies not answer the question, but you could consider also side by side bar plots for this kind of data (frequency by date bin for two categories):

library(tidyverse)
#Code 2
df %>% pivot_longer(-1) %>%
  ggplot(aes(x=birthy,y=value,fill=name,group=name))+
  geom_col(position = position_dodge2(),width = 0.7)

enter image description here

denis
  • 5,580
  • 1
  • 13
  • 40