按两组比较两个数值变量

时间:2019-09-06 05:57:48

标签: r ggplot2

我如何通过两组将x轴上的两个数字变量作为均值和sd构建ggplot2图?例如:左手术前Hb值分为2组,右手术后Hb值相同的两组。

enter image description here

1 个答案:

答案 0 :(得分:3)

这与您要寻找的东西相似吗?

library(tidyverse)
library(reshape2)

# creating some nonsense sample data
x <- iris %>%
  select(-Petal.Width,-Sepal.Width) %>%
  melt(id.vars="Species") %>%
  group_by_at(colnames(select_if(.,negate(is.numeric)))) %>%
  summarise_all(mean,na.rm=T) %>%
  mutate(sd01=value-value/10,
         sd02=value+value/10) %>%
  rename(mean=value,
         groups=variable)

# plotting
ggplot(x,aes(Species,mean,color=Species))+
  geom_point(stat="identity")+
  geom_errorbar(aes(ymin=sd01,ymax=sd02))+
  facet_wrap(~groups, strip.position = "bottom")+
  theme(axis.ticks = element_blank(),
        strip.background = element_blank(),
        strip.text.x = element_text(),
        panel.spacing = unit(0, "lines"))+
  scale_y_continuous(expand=c(0,0))+
  annotate("segment", x = 0, y = 0, xend = 4, yend = 0)

enter image description here

编辑:使用geom_pointrange()可使代码更短并更改错误栏的外观。

ggplot(x,aes(Species,mean,color=Species))+
  geom_pointrange(aes(ymin=sd01,ymax=sd02),stat="identity")+
  facet_wrap(~groups, strip.position = "bottom")+...

enter image description here