0

I have the following graph (below) that I would like to add a trend line to. However, I am having the same issue as this person has previously outlined: geom_smooth in ggplot2 not working/showing up.

However, I am unable to change the date to a data using as.date because it will not recognise only year e.g. 1999 as a date format (as opposed to dd-mm-yy).

Is there a simple way to get round this and add a trend line to the graph?

df <- data.frame(Year = c("2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022"),
                 Proportion = c(46, 51, 48, 66, 60, 73, 61, 73, 60, 68, 74, 65)
)

#Create plot, labels etc.
graph1 <- ggplot(df, aes(x = Year, y = Proportion)) + 
  geom_point() +
  labs(title = "",
       x = "Year",
       y = "Proportion (%)") +
  theme_classic(base_size = 20) +
  geom_point(size = 3, colour = "red2") +
  scale_y_continuous(limits = c(20, 80), breaks = seq(20, 80, by = 10)) 

graph1

5
  • 1
    as.Date(paste0(Year, "-01-01")) will come out as a Date-class column Commented Sep 11, 2023 at 19:47
  • transform(df, Date = as.Date(paste0(Year, "-01-01"))) |> ggplot(aes(x = Year, y = Proportion)) + geom_point() + ... Commented Sep 11, 2023 at 19:48
  • 1
    Imperfectly a dupe of stackoverflow.com/q/9322923/3358272, stackoverflow.com/q/6242955/3358272 (which have "Y-m", not just "Y" as you have here, but the solution is effectively the same). Commented Sep 11, 2023 at 19:49
  • 3
    If all you have is years, you can treat them as numbers instead of dates. Try x = as.numeric(Year) instead of x = Year. The geom_smooth will work perfectly well. Commented Sep 11, 2023 at 19:52
  • Or yet another way, specify your grouping manually. Adding group = 1 to the aes() call will also work. Commented Sep 11, 2023 at 21:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.