Apologies in advance for any StackOverflow conventions I may break here - this is my first post!
I'm having an issue with faceting - specifically, with the order of the plots produced by facet_wrap
, which do not 'follow their labels' when I attempt to reorder the underlying factor.
My data is a large CSV file of car park occupancy data for my local area (I can link to the page as a comment if someone needs it, but I am currently restricted to 2 links per post and I need them later!).
# Separate interesting columns from df (obtained from CSV)
df3 <- df[!(df$Name == "test car park"), c("Name", "Percentage", "LastUpdate")]
# Convert LastUpdate to POSIXct and store in a new vector
updates <- as.POSIXct(df4$LastUpdate, format = "%d/%m/%Y %I:%M:%S %p",
tz = "UTC")
# Change every datatime to "time to nearest 10 minutes" (600 seconds)
times <- as.POSIXct(round(as.double(updates) / 600) * 600,
origin = as.POSIXlt("1970-01-01"), tz = "UTC")
decimal_times <- as.POSIXlt(times)$hour + as.POSIXlt(times)$min/60
# Change every datetime to weekday abbreviation
days <- format(updates, "%a")
# Add these new columns to our dataframe
df4 <- cbind(df3, "Day" = days, "Time" = decimal_times)
# Take average of Percentage over each time bin, per day, per car park
df5 <- aggregate(df4$Percentage,
list("Time" = df4$Time, "Day" = df4$Day, "Name" = df4$Name),
mean)
#####
# ATTEMPTED SOLUTION: Re-order factor (as new column, for plot comparison)
df5$Day1 <- factor(df5$Day, levels = c("Mon", "Tue", "Wed", "Thu",
"Fri", "Sat", "Sun"))
#####
These are the plots subsequently produced from df5
, with facet_wrap(~ Day)
and facet_wrap(~ Day1)
respectively:
Notice how the facet labels have changed (as desired) - but the plots have not moved with them. Can anyone enlighten me as to what I am doing wrong? Thanks in advance!
Note: The plot is correct when faceted by Day
- and hence currently incorrect when faceted by Day1
.
Edit: Here is the code for generating the plots:
p <- ggplot(data = df5, aes(x = as.double(Time), y = df5$x, group = Name)) +
facet_wrap(~ Day) + labs(y = "Percentage occupancy", x = "Time (hour)") +
geom_line(aes(colour = Name)) +
guides(colour = guide_legend(override.aes = list(size = 3)))
p
where Day
is changed for Day1
in the second plot.