如何使用R中的geom_errorbar()来反转出现错误条的顺序?

时间:2017-11-22 22:55:30

标签: r plot ggplot2

我有以下示例图:

test <- data.frame("Factor" = as.factor(c("O", "C", "A")), 
                       b = c(0.18, .34, .65, -.13, .38, .26), 
                       lower95 = c(-.1, .09, .34, -.52, .10, -.02), 
                       upper95 = c(.48, .58, .98, .26, .67, .56), 
                       group = factor(c("Experiment 1","Experiment 2")))

test$Factor <- factor(test$Factor, as.character(test$Factor))
test$group <- factor(test$group, as.character(test$group))

ggplot(test, aes(Factor, b, colour = group)) +
  geom_errorbar(aes(ymin = lower95, ymax = upper95), 
            size = 1,
            width = .5, 
            position = 'dodge') +
  geom_hline(yintercept = 0) +
  ylim(-1.25, 1.25) +
  coord_flip() +
  theme_bw() + 
  ggtitle("Title") +
  theme(
axis.text=element_text(size = 20), 
axis.title=element_text(size = 18),
plot.title = element_text(size = 20, face = "bold"),
axis.text.y=element_text(size = 12)
  )

正如您所见,错误栏以相反的顺序(从上到下)显示,就像在图例中一样。我希望实验1误差条显示在实验2误差条上方。

我试过了

ggplot(test, aes(Factor, b, colour = forcats::fct_rev(groups)

但这会颠倒图例中组标签的顺序,而不是图例中颜色的顺序 - 这是可行的。我也尝试颠倒我在数据框中输入它们的顺序,但这并没有解决问题。

我会感激一些帮助!

2 个答案:

答案 0 :(得分:2)

重新分解将改变绘图的顺序,但是,如您所见,也会更改图例的顺序。除了反转group的级别之外,您还可以使用reverse中的guide_legend参数反转图例的显示顺序。

ggplot(test, aes(Factor, b, colour = forcats::fct_rev(group))) +
     geom_errorbar(aes(ymin = lower95, ymax = upper95), 
                   size = 1,
                   width = .5, 
                   position = 'dodge') +
     geom_hline(yintercept = 0) +
     ylim(-1.25, 1.25) +
     coord_flip() +
     theme_bw() + 
     ggtitle("Title") +
     theme(
          axis.text=element_text(size = 20), 
          axis.title=element_text(size = 18),
          plot.title = element_text(size = 20, face = "bold"),
          axis.text.y=element_text(size = 12)
     ) +
     guides(color = guide_legend(reverse = TRUE) )

enter image description here

如果您使用scale_color_discretescale_color_manual来控制其他比例元素,例如图例名称,则可以使用guide_legend而不是guides

+
scale_color_discrete(name = "Experiment", guide = guide_legend(reverse = TRUE) )

答案 1 :(得分:0)

你的意思是这样吗?

test$Factor <- factor(test$Factor, levels = rev(levels(test$Factor)));
test$group <- factor(test$group, levels = rev(levels(test$group)));

ggplot(test, aes(Factor, b, colour = group)) +
  geom_errorbar(aes(ymin = lower95, ymax = upper95),
            size = 1,
            width = .5,
            position = 'dodge') +
  geom_hline(yintercept = 0) +
  ylim(-1.25, 1.25) +
  coord_flip() +
  theme_bw() +
  ggtitle("Title") +
  theme(
axis.text=element_text(size = 20),
axis.title=element_text(size = 18),
plot.title = element_text(size = 20, face = "bold"),
axis.text.y=element_text(size = 12)
  )

enter image description here

我不清楚你是否也要反转test$Factor的顺序;只是(联合国)根据你所追求的内容评论相应的行。