I am plotting a graph using ggplot2 in RStudio and I am having a hard time trying to figure out where I have gone wrong in my R codes regarding the sort order of a column in my data set named 'Mth'.
My data set is called data1
and it has only 2 columns, namely Age
and Mth
My codes stand as follows:
library(ggplot2)
data1 <- read.csv("myfile.csv", as.is=TRUE, header = TRUE)
Month <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
Month2 <- factor (Month,
levels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"),
ordered = TRUE)
mean_age <- data1 %>%
filter(Mth %in% Month2) %>%
group_by(Mth) %>%
summarize(xbar = round(mean(Age, na.rm = TRUE), 0))
mean_age$y <- 0.3
yr_labs <- data.frame(x = 85, y = 0.8,
Mth = Month2)
p <- ggplot(subset(data1, Mth %in% Month2), aes(x = Age))
p1 <- p + geom_density(fill = "gray20", color = FALSE,
alpha = 0.9, mapping = aes(y = ..scaled..)) +
geom_vline(data = subset(mean_age, Mth %in% Month2),
aes(xintercept = xbar), color = "white", size = 0.5) +
geom_text(data = subset(mean_age, Mth %in% Month2),
aes(x = xbar, y = y, label = xbar), nudge_x = 1.2,
color = "white", size = 3.5, hjust = 1) +
geom_text(data = subset(yr_labs, Mth %in% Month2),
aes(x = x, y = y, label = Mth)) +
facet_grid(Mth ~ ., switch = "y")
And here is the output of the current codes:
As can be seen, the months (Mth
column in my data set) is not respecting the sort order I created above.
What am I doing wrong?