01横向柱形图
2022-12-05 本文已影响0人
Jachin111
构造柱形图的数据集
set.seed(1234)
x <- seq(5,10,by=0.5)
df <- data.frame(`s_Klebsiella_phage_vB_KpnP_SU552A`=sample(x,10,replace=T),
`s_Escherichia_phage_ECBP5`=sample(x,10,replace=T),
`s_Clostridium_phage_phi8074-B1`=sample(x,10,replace=T),
check.names=F)
head(df)
宽格式转换为长格式
library(dplyr)
df %>% reshape2::melt() -> df1
分组求均值和标准差
df %>%
reshape2::melt() %>%
group_by(variable) %>%
summarise(mean_value=mean(value),
sd_value=sd(value)) -> df2
柱状图叠加误差线和散点图
library(ggplot2)
ggplot() +
geom_col(data=df2,aes(x=variable,y=mean_value),
fill="#8babd3",
color="black") +
geom_errorbar(data=df2,aes(x=variable,
ymin=mean_value-sd_value,
ymax=mean_value+sd_value),
width=0.2) +
geom_jitter(data=df1,aes(x=variable,y=value),
width=0.2,color="grey")
image.png
调整坐标,让屁股朝右
ggplot() +
geom_col(data=df2,aes(x=variable,y=mean_value),
fill="#8babd3",
color="black") +
geom_errorbar(data=df2,aes(x=variable,
ymin=mean_value-sd_value+0.001,
ymax=mean_value+sd_value),
width=0.2) +
geom_jitter(data=df1,aes(x=variable,y=value),
width=0.2,color="grey") +
## scale_y_continuous(expand=c(0,0)) +
theme_bw() +
coord_flip() +
scale_y_reverse(expand=c(0,0),
position="right") +
labs(x=NULL,y=NULL) -> p1
image.png
第二个柱形图也用这个数据
ggplot() +
geom_col(data=df2,aes(x=variable,y=mean_value),
fill="#ffc080",
color="black") +
geom_errorbar(data=df2,aes(x=variable,
ymin=mean_value-sd_value+0.001,
ymax=mean_value+sd_value),
width=0.2) +
geom_jitter(data=df1,aes(x=variable,y=value),
width=0.2,color="grey") +
scale_y_continuous(expand=c(0,0)) +
theme_bw() +
coord_flip() +
labs(x=NULL,y=NULL) +
theme(axis.text.y=element_blank(),
axis.ticks.y=element_blank()) -> p2
image.png
构造最右侧的热图数据
df3 <- data.frame(x="A",
y=c("s_Klebsiella_phage_vB_KpnP_SU552A",
"s_Escherichia_phage_ECBP5",
"s_Clostridium_phage_phi8074-B1"),
group=c("f_Siphoviridae",
"f_Podoviridae",
"f_Podoviridae"))
ggplot(df3,aes(x=x,y=y)) +
geom_tile(aes(fill=group),show.legend=F) +
labs(x=NULL,y=NULL) +
scale_x_discrete(expand=c(0,0)) +
scale_y_discrete(expand=c(0,0),
position="right",
labels=c("f_Podoviridae","","f_Siphoviridae")) +
theme(panel.background=element_blank(),
axis.ticks=element_blank(),
axis.text.x=element_blank()) +
scale_fill_manual(values=c("#c65911","#ffd965")) -> p3
image.png
拼图
library(patchwork)
p1+p2+p3+ggtitle("Bacteriophages") +
theme(plot.title=element_text(hjust=5)) +
plot_layout(widths=c(1.2,1,0.2)) -> p
ggsave("Rplot.pdf",p,width=10,height=3)
image.png