根据ggplot中的两个条件对条形图进行排序

Sort a bar plot based on two conditions in ggplot

我想创建一个排列成 的条形图,并在这些组内,从 * 最小值到最大值 排序值。

为了重新创建示例,我将使用以下数据框

df <- data.frame(
  stringsAsFactors = FALSE,
             Sites = c("Site 1","Site 2","Site 3",
                       "Site 4","Site 5","Site 6","Site 7","Site 8","Site 9",
                       "Site 10","Site 11"),
            Values = c(184.7955548,171.1466314,
                       245.5952181,188.3072784,259.9438698,210.3448318,
                       173.7977541,182.5497301,198.7985429,188.0458496,215.5709303),
            Groups = c(1, 1, 3, 3, 2, 3, 1, 3, 3, 2, 2))

对于我使用的情节:

df %>% arrange(Groups, Values) %>%
  mutate(name=factor(Groups, levels = Values)) %>%
  ggplot(aes(x = df$Sites, y = df$Values))+
  geom_bar(stat = "identity", fill = df$Groups)+
  scale_color_manual(values = c ('royalblue1', 'slategrey2', 'yellow1'))+
  ylab("Values")+
  xlab("")+
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

导致:

但我期待的是以下内容:

如有任何帮助,我们将不胜感激

代码中的几个问题 -

  • name=factor(Groups, levels = Values) 给出所有 NAlevels 应该是数据中存在的值。
  • ggplot 代码中不需要 $。另外 df$Sites 没有我们需要的因子水平。因子水平添加到管道数据中,而不是原始数据中。
library(dplyr)
library(ggplot2)

df %>% 
    arrange(Groups, Values) %>%
    mutate(Sites=factor(Sites, levels = Sites), 
           Groups = factor(Groups)) %>% 
    ggplot(aes(x = Sites, y = Values, fill = Groups)) +
    geom_bar(stat = "identity")+
    scale_fill_manual(values = c ('royalblue1', 'grey2', 'yellow1'))+
    ylab("Values")+
    xlab("")+
    theme(axis.text.x = element_text(angle = 90, hjust = 1))