我有一个小节,更改了样本“ 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
fro时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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句