Reputation: 41
How I can build ggplot2 graph with two numeric variables on x axis as mean and sd, by two groups? As an example: on the left hand preoperative Hb value, by 2 groups and on the right the postoperative Hb values by the same 2 groups.
Upvotes: 2
Views: 464
Reputation: 1102
Is this similar to what you're looking for?
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)
EDIT: using geom_pointrange()
makes the code shorter and changes the look of the errorbar.
ggplot(x,aes(Species,mean,color=Species))+
geom_pointrange(aes(ymin=sd01,ymax=sd02),stat="identity")+
facet_wrap(~groups, strip.position = "bottom")+...
Upvotes: 3