0

Hey I want to make a visualization of the mean number of children a woman has against the years with a time trend.

I've tried

mean_children_yearly <- aggregate(kids ~ year, fertility, FUN = mean)       
plot(mean_children_yearly, xlim=c(2002,2014),
      ylim=c(range(mean_children_yearly[,2])))

To get a visualization but cannot seem to add in a trend line Futhermore I tried working with time series

a <- ts(mean_children_yearly)
plot(a) 

but that does not put the years on the x-axis. How can I get the years on the x-axis?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453

1 Answers1

0

Make up a data set to work with:

set.seed(101)
fertility <- data.frame(year = rep(2000:2010, each = 5),
                 kids = sample(0:5, size = 55, replace = TRUE))

When you make the whole thing a time series, you get a plot of year vs index (silly) and kids vs index. Assuming your data are yearly, this is a little more sensible:

a <- ts(mean_children_yearly$kids, start = 2000)
plot(a)

but it doesn't give you a time trend.

You could do this to add a trend line to the original plot:

m <- lm(kids ~ year, data = mean_children_yearly)
plot(mean_children_yearly)
abline(m)

Or, if you want to go down the ggplot rabbit hole:

library(ggplot2)
ggplot(mean_children_yearly) +
   aes(x = year, y = kids) +
   geom_point() +
   geom_smooth(method = "lm")
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453