ggplot2 faceting - 重新排序标签时未重新排序的图表

时间:2016-11-16 12:26:54

标签: r plot ggplot2 facet

预先为任何StackOverflow约定道歉我可能会在这里打破 - 这是我的第一篇文章!

我遇到了分面问题 - 特别是facet_wrap制作的地块的顺序,它们没有跟随他们的标签'当我试图重新排序潜在因素时。

我的数据是我所在地区的停车场占用数据的大型CSV文件(如果有人需要,我可以将该链接到该页面作为评论,但我目前限制为每个帖子有2个链接,我以后需要它们! )。

# 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_Dayfacet_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的{​​{1}}已更改。

1 个答案:

答案 0 :(得分:0)

您使用的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)

day plot

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)

day1 plot

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

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

值相同但系数级别的顺序已更改。