首页 > 解决方案 > 防止在 facet_wrap() 中重新排序

问题描述

我的 ggplot() 重新排序数据时遇到问题。我在下面有一个示例代码。我有数据,并重新排序了内容中的因子,但是在 facet_wrap() 中的 str_extract() 之后,数据在我重新排序之前被重新排序。有没有办法防止这种情况发生?对于我的实际代码,在 ggplot 的 facet_wrap() 中使用正则表达式对我来说很重要,

data <- chickwts
data <- mutate(data, time = 1:nrow(data))
lvl <- c("linseed", "meatmeal", "sunflower", "soybean", 
         "casein", "horsebean")
data$feed <- factor(data$feed, levels = lvl)
ggplot(data, aes(x = time, y = weight, color = feed)) +
    geom_line(size = 1) + geom_point(size = 1.75) +
    facet_wrap(~str_extract(feed,"[a-z]+"))

标签: rggplot2facet-wrap

解决方案


你可以把factor里面facet_wrap

ggplot(data, aes(x = time, y = weight, color = feed)) +
    geom_line(size = 1) + geom_point(size = 1.75) +
    facet_wrap(~ factor(str_extract(feed,"[a-z]+"), levels = lvl))

在此处输入图像描述


推荐阅读