我有一个小节,我更改了样本“ 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"))
您可以将position_dodge2
与reverse = 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))
编辑:使用geom_errobar
添加position_dodge2
如本讨论中的文档https://github.com/tidyverse/ggplot2/issues/2251所述,从position_dodge2
到geom_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))