ggplot2 faceting - 标签重新排序时绘图不重新排序

ggplot2 faceting - plots not reordered when labels reordered

对于我在这里可能违反的任何 Whosebug 惯例提前致歉 - 这是我的第一个 post!

我在分面方面遇到问题 - 特别是 facet_wrap 生成的图的顺序,当我尝试重新排序基础因子时 'follow their labels' 没有。

我的数据是我所在地区的停车场占用数据的大型 CSV 文件(如果有人需要,我可以 link 到页面作为评论,但我目前限制为 2 links per post,我稍后需要它们!)。

# 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"))
#####

这些是随后从 df5 生成的图,分别为 facet_wrap(~ Day)facet_wrap(~ Day1)

facet_Day, facet_Day1

注意小平面标签是如何改变的(根据需要)——但是绘图并没有随之移动。谁能告诉我我做错了什么?提前致谢!

注意:当 Day 分面时,该图是正确的 - 因此当 Day1.

分面时,该图目前不正确

编辑: 下面是生成图表的代码:

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

其中 Day 在第二个图中更改为 Day1

您使用的 factor levels 重新排序似乎至少适用于该小示例:

library(ggplot2)
dtf <- data.frame(day = c("Mon", "Tue", "Wed", "Thu",
                          "Fri", "Sat", "Sun"),
                  value = 1:7)
ggplot(dtf, aes(x = value, y = value)) + 
    geom_point() + facet_wrap(~day)

dtf$day1 <- factor(dtf$day, levels = c("Mon", "Tue", "Wed", "Thu",
                                       "Fri", "Sat", "Sun"))
ggplot(dtf, aes(x = value, y = value)) + 
    geom_point() + facet_wrap(~day1)

让我们看一下数据框的结构:

str(dtf)
# 'data.frame': 7 obs. of  3 variables:
# $ day  : Factor w/ 7 levels "Fri","Mon","Sat",..: 2 6 7 5 1 3 4
# $ value: int  1 2 3 4 5 6 7
# $ day1 : Factor w/ 7 levels "Mon","Tue","Wed",..: 1 2 3 4 5 6 7

值相同,但因子水平的顺序已更改。