更改集群 geom_col 中的填充顺序?

Changing the fill order in a clustered geom_col?

我正在尝试手动重新排序我的地块内的条形簇。这是整个相关数据集:

Season  Set Density
Summer  Full set    0.020065
Summer  Set 2   0.017713
Summer  Set 3   0.015170
Summer  Set 4   0.018816
Autumn  Full set    0.009459
Autumn  Set 2   0.007937
Autumn  Set 3   0.008498
Autumn  Set 4   0.011544
Winter  Full set    0.017685
Winter  Set 2   0.015451
Winter  Set 3   0.013294
Winter  Set 4   0.016717
Spring  Full set    0.021445
Spring  Set 2   0.018672
Spring  Set 3   0.016526
Spring  Set 4   0.019715

ggplot 代码:

plot <-
  ggplot(arrange(data1day, Season), aes(x = Set, y = 100 * Density, fill = Season)) +
  geom_col(position = 'dodge', color = 'black') +
  theme_classic() +
  labs(x = "Subset of sites surveyed", y = "Density (%)") +
  scale_x_discrete(limits = c("Full set", "Set 2", "Set 3", "Set 4")) +
  scale_fill_brewer(limits = c("Summer", "Autumn", "Winter", "Spring"), palette = "Set2") +
  theme(text = element_text(size = 14, family = "serif", colour = "black")) +
  theme(axis.text.x = element_text(colour = "black")) +
  theme(axis.text.y = element_text(colour = "black"))

图例以正确的顺序列出了季节(夏季、秋季、冬季,Spring)并且颜色和条形对应于正确的数据(秋季始终最低)但条形不正确匹配图例的顺序。我似乎无法在其他任何地方找到如何执行此操作。

您可以使用fct_relevel

library(dplyr)

data1day %>%
  arrange(Season) %>%
  mutate(Season = as.factor(Season),
         Season = fct_relevel(Season, "Summer", "Autumn", "Winter", "Spring")) %>%
  ggplot( aes(x = Set, y = 100 * Density, fill = Season)) +
  geom_col(position = 'dodge', color = 'black') +
  theme_classic() +
  labs(x = "Subset of sites surveyed", y = "Density (%)") +
  scale_x_discrete(limits = c("Full set", "Set 2", "Set 3", "Set 4")) +
  scale_fill_brewer(limits = c("Summer", "Autumn", "Winter", "Spring"), palette = "Set2") +
  theme(text = element_text(size = 14, family = "serif", colour = "black")) +
  theme(axis.text.x = element_text(colour = "black")) +
  theme(axis.text.y = element_text(colour = "black"))