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

心电图

我有一个小节,更改了样本“ 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"))

在此处输入图片说明

dc37

您可以使用position_dodge2与参数reverse = TRUEgeom_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_dodge2fro时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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

更改ggplot上的geom_bar宽度

R:ggplot geom_bar填充顺序未遵循级别

更改堆叠Geom_Bar的顺序

控制ggplot2 geom_bar的填充顺序和组

排序并填充2个不同的变量geom_bar ggplot2 R

在 ggplot 中使用 geom_bar(position="fill, stat = "identity) 翻转填充变量

ggplot2:geom_bar(); 如何更改填充顺序,以使条形图不会在较高值的条形图内丢失?

ggplot2:geom_bar填充颜色;如何更改为不同的数据分组

使用正值和负值控制 ggplot::geom_bar position_stack 在图形和图例中的填充颜色顺序

ggplot geom_bar在x轴上具有单独的分组变量

ggplot2,geom_bar,闪避,条形顺序

ggplot:geom_bar 堆叠顺序和标签

ggplot geom_bar()不填充图上的色条

ggplot2 geom_bar填充美学不变

更改 geom_bar ggplot 中 20% 条的颜色

更改 ggplot 上显示的变量类型的顺序

geom_bar,基于变量更改列之间的距离

在ggplot2中的geom_bar上重叠文本

ggplot geom_bar的比例

ggplot并排geom_bar()

更改ggplot填充

ggplot更改图例中的geom顺序

使用 ggplot2 和 geom_bar 根据 1 个因子变量和基于另一个因子变量的条形图案更改条形颜色

ggplot geom_bar根据条件使用单独的颜色填充连续颜色

ggplot geom_bar()通过线型自定义并填充

ggplot (geom_bar) 中的十分位数填充

更改ggplot上的颜色

在更改 geom_bar 顺序时保持一致的颜色?

R ggplot geom_bar:更改条形内的透明度,保持轮廓/边界相同