I'm trying to create a plot based on weeks in the year and ratings. For some reason my x-axis is not in the order of my data set, even though I have arranged it specifically.
For example:
library(dplyr)
library(ggplot2)
df <- df %>%
arrange(match(weeks, c("0", "1 - 2022", "2 - 2022", "3 - 2022", "4 - 2022", "5 - 2022", "6 - 2022", "7 - 2022", "8 - 2022", "9 - 2022", "10 - 2022",
"11 - 2022", "12 - 2022", "13 - 2022", "14 - 2022", "15 - 2022", "16 - 2022", "17 - 2022", "18 - 2022", "19 - 2022", "20 - 2022",
"21 - 2022", "22 - 2022", "23 - 2022", "24 - 2022", "25 - 2022", "26 - 2022", "27 - 2022")))
eloRatingss %>%
ggplot(aes(x = weeks, y = rating))
geom_point()
geom_line()
And this is the output I'm getting:
How can I fix this so my x-axis is the same as my arranged values above?
Thanks!
CodePudding user response:
Coerce weeks
to factor setting the levels in numeric order.
The levels are sorted with str_sort(., numeric = TRUE)
from package stringr
.
suppressPackageStartupMessages({
library(dplyr)
library(ggplot2)
})
df1 %>%
pull(weeks) %>%
unique() %>%
stringr::str_sort(numeric = TRUE) -> levs_weeks
df1 %>%
mutate(weeks = factor(weeks, levels = levs_weeks)) %>%
ggplot(aes(weeks, rating, group = 1))
geom_point()
geom_line()
theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust=1))
Created on 2022-10-19 with reprex v2.0.2
Test data
Note that I make sure there is no weeks
variable by removing it, the levels are created and sorted in the code above.
weeks <- c("0", "1 - 2022", "2 - 2022", "3 - 2022", "4 - 2022", "5 - 2022", "6 - 2022", "7 - 2022", "8 - 2022", "9 - 2022", "10 - 2022",
"11 - 2022", "12 - 2022", "13 - 2022", "14 - 2022", "15 - 2022", "16 - 2022", "17 - 2022", "18 - 2022", "19 - 2022", "20 - 2022",
"21 - 2022", "22 - 2022", "23 - 2022", "24 - 2022", "25 - 2022", "26 - 2022", "27 - 2022")
set.seed(2022)
df1 <- data.frame(
weeks = sample(weeks),
rating = sample(2000:2500, length(weeks))
)
rm(weeks)
Created on 2022-10-19 with reprex v2.0.2