更改 ggplot 上的填充变量顺序 geom_bar

Change order of filling variable on a ggplot geom_bar

我有一个条形图,我更改了样本的顺序 "BB" "AA"。它们由条件位置填充。

如何更改图例变量填充的顺序,使条形图显示为华盛顿-蒙古-埃及? (即:黑柱(埃及)在右边,然后是蒙古,然后白柱(华盛顿)在左边)。

sample <- c("AA", "AA", "AA", "BB", "BB", "BB")
location<- c("Washington", "Mongolia", "Egypt", "Washington", "Mongolia", "Egypt" )
value <- c(0.03, 0.06, 0.02, 0.0051, 0.0082, 0.003)
data <- data.frame(sample, location, value)


ggplot(data, aes(fill=location, y=value, x=sample)) + 
    geom_bar(position="dodge", stat="identity", color="black")+
theme_classic()+
 scale_fill_grey() +
  scale_x_discrete(limits=c("BB", "AA"))

您可以将 position_dodge2geom_col 中的参数 reverse = TRUE 一起使用(相当于 geom_bar(stat = "identity"))。

我还使用guides(fill = guide_legend(reverse = TRUE))反转图例标签并匹配条形图的顺序

library(ggplot2) 

ggplot(data, aes(fill=location, y=value, x=sample)) + 
  geom_col(position = position_dodge2(reverse = TRUE) color="black")+
  theme_classic()+
  scale_fill_grey() +
  scale_x_discrete(limits=c("BB", "AA"))+
  guides(fill = guide_legend(reverse = TRUE))


编辑:使用 position_dodge2

添加 geom_errobar

如本次讨论 (https://github.com/tidyverse/ggplot2/issues/2251) 所述,当使用 position_dodge2geom_col 时,如果你想添加 geom_errorbar,你需要使用 padding 参数:

sample <- c("AA", "AA", "AA", "BB", "BB", "BB")
location<- c("Washington", "Mongolia", "Egypt", "Washington", "Mongolia", "Egypt" )
value <- c(0.03, 0.06, 0.02, 0.0051, 0.0082, 0.003)
sd <- c(0.003, 0.0012, 0.0015, 0.00025, 0.0002, 0.0001) 
data <- data.frame(sample, location, value, sd)

library(ggplot2)

ggplot(data, aes(fill=location, y=value, x=sample)) + 
  geom_bar(position = position_dodge2(reverse = TRUE), stat="identity", color="black")+
  theme_classic()+
  scale_fill_grey() +
  scale_x_discrete(limits=c("BB", "AA"))+
  guides(fill = guide_legend(reverse = TRUE))+
  geom_errorbar(aes(ymin = value-sd, ymax = value+sd), 
                position = position_dodge2(reverse = TRUE, padding = 0.6, width = 0.5))