I am trying to add a line to my bar graph showing the % difference of the years. I was trying to create a function:
year_pct_change <- function(x) {
x <- x[order(x$Year, decreasing = TRUE), ] # Confirms ordered by decreasing year
pct_change <- -diff(x$Value)/x$Value[-1] * 100 # Gets percent change in profit from preceding year
data.frame(year = x$YEAR[-length(x$YEAR)], pct_change = pct_change) # Returns data frame
}
code for the ggplot:
ggplot(Enrolment)
geom_bar(aes(x=Year, y=Value),stat="identity", fill="cyan")
geom_line(aes(x=Year, y=year_pct_change),stat="identity",color="red",size=2) ,
x="Year",y="Student Count")
it just throws me an error
Error in
f()
: ! Aesthetics must be valid data columns. Problematic aesthetic(s): y = year_pct_change. Did you mistype the name of a data column or forget to add after_stat()? Runrlang::last_error()
to see where the error occurred.
Any suggestions on how to add a percent difference line to my bar graph? I'm aiming to have something like this..
CodePudding user response:
library(dplyr)
library(ggplot2)
year_pct_change <- function(x) {
x[order(x$Year, decreasing = FALSE), ]
x <- x |> mutate(year_pct_change = 100*((Value - lag(Value))/lag(Value)))
}
Enrolment <- year_pct_change(Enrolment)
ggplot(Enrolment)
geom_bar(aes(x=Year, y=Value),stat="identity", fill="cyan")
geom_line(aes(x=Year, y=year_pct_change),stat="identity", color="red", size=2)
A couple of changes to the function.
- Decreasing now FALSE.
- New formula for % change (to match lengths of arguments and calc % (as pointed out by Rui).
- Last line of your function unneeded now.
As there is only one y axis, you are unlikely to have the % change and Value with similar ranges.
There was a fragment at the end of your ggplot2 call that I left out: x="Year",y="Student Count"