条形图上带有负值的水平标准误差线

时间:2019-02-21 05:08:24

标签: r ggplot2

我有一个看起来像这样的条形图: Horizontal Bar Graph

并且我正在尝试在其上获得标准误差线-所以每列有两个标准误差线(一个用于正Y,一个用于负N)。我知道geom_errorh,但无法使它适用于这种条形图。 这是一个具有可重现性的示例,其中包含我用来获取上面的条形图的代码:

数据框

Behavior<-as.character(c("Hammock","Hammock","Climbing Trees","Climbing Trees","Structures","Structures","Grade","Grade"))
Presence<-c("Y","N","Y","N","Y","N","Y","N")
Mean<-as.numeric(c("18.5", "-6.4","3.5","-6.8","13.2","-10.1","4.7","-2.3"))
SD<-as.numeric(c("17.6","-11.9","1.2","-4.4","3.6","-6.25","1.23","-0.4"))
DF<-data.frame(Behavior,Presence,Mean,SD)

Coord Flip Geom Bar

brks <- seq(-20, 20, 2)
lbls = paste0(as.character(c(seq(-20, 0, 2), seq(2, 20, 2))), "")



ggplot(DF, aes(x = Behavior, y = Mean, fill = Presence )) + 
      geom_bar(data = subset(DF, Presence == "N"), stat = "identity") +
      geom_bar(data = subset(DF, Presence == "Y"), stat = "identity") +
      scale_y_continuous(breaks = brks,labels = lbls) + 
      scale_fill_manual(values=c("#0b6bb6", "#6eaf46"),name="", breaks=c("N", "Y"),labels=c("N", "Y"))+
      coord_flip()+  
      theme_bw()+
      xlab("Pen Characteristic - Behavior")+
      ylab("Average Behavior per Session")+

是否可以在这种类型的图形上获得SE条?

谢谢!

1 个答案:

答案 0 :(得分:0)

正如@Jakub在评论中指出的那样,SD值为正值。

您通常会执行以下操作:

library(ggplot2)
set.seed(1)

Behavior <- as.character(c(
  "Hammock","Hammock",
  "Climbing Trees","Climbing Trees",
  "Structures","Structures",
  "Grade","Grade"))
Presence <- c("Y","N","Y","N","Y","N","Y","N")
Mean <- as.numeric(
  c("18.5", "-6.4",
    "3.5","-6.8",
    "13.2","-10.1",
    "4.7","-2.3"))
SD <- as.numeric(c(
  "17.6","-11.9",
  "1.2","-4.4",
  "3.6","-6.25",
  "1.23","-0.4"))
my_sd <- runif(length(Behavior))
DF <- data.frame(Behavior,Presence,Mean,SD, my_sd)

brks <- seq(-20, 20, 2)

ggplot(DF, 
       aes(x=Behavior, y=Mean, fill=Presence )) + 
  geom_col() +
  scale_y_continuous(breaks = brks) + 
  scale_fill_manual(values=c("#0b6bb6", "#6eaf46"),
                    name="", 
                    breaks=c("N", "Y"),
                    labels=c("N", "Y")) +
  coord_flip()+  
  theme_bw()+
  xlab("Pen Characteristic - Behavior") +
  ylab("Average Behavior per Session") +
  geom_errorbar(aes(ymin=Mean - my_sd, ymax=Mean + my_sd))