This question already has an answer here:
Issue when passing variable with dollar sign notation ($) to aes() in combination with facet_grid() or facet_wrap()

(1个答案)


3年前关闭。





对于任何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_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)


r - ggplot2构面-标签重新排序时,图未重新排序-LMLPHP

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)


r - ggplot2构面-标签重新排序时,图未重新排序-LMLPHP

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

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


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

关于r - ggplot2构面-标签重新排序时,图未重新排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40632189/

10-15 10:29