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

问题描述 投票:1回答:1

我有一个小节,我更改了样本“ BB”“ AA”的顺序。它们由条件位置填充。

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

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"))

enter image description here

r ggplot2 geom-bar
1个回答
1
投票

您可以将position_dodge2reverse = TRUE中的参数geom_col结合使用(等效于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))

enter image description here


编辑:使用geom_errobar添加position_dodge2

如本讨论中的文档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))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.