ggplot2绘图学习 一文带你掌握如何添加各种bar
之前我们学习了ggplot绘制单变量,两个连续变量的图形,两个离散型变量。对于一个离散型变量,一个连续型变量,有很多作图方式,包括箱图,点图等等
· geom_boxplot() for box plot
· geom_violin() for violin plot
· geom_dotplot() for dot plot
· geom_jitter() for stripchart
· geom_line() for line plot
· geom_bar() for bar plot
今天我们介绍一下如何添加bar
先建立一个数据
library(tidyverse)
# ToothGrowth data set
df <- ToothGrowth
df$dose <- as.factor(df$dose)
head(df, 3)
通过dose分组,求每一组的len值得平均值和标准差
df2 <- df %>%
group_by(dose) %>%
summarise(
sd = sd(len),
len = mean(len)
)
head(df2)
构建图层
f <- ggplot(df2, aes(x = dose, y = len,
ymin = len-sd, ymax = len+sd))
有不同种类的bar
Cross bar
f + geom_crossbar()
# 颜色分组
f + geom_crossbar(aes(color = dose))
# 手动设置颜色
f + geom_crossbar(aes(color = dose)) +
scale_color_manual(values = c("#999999", "#E69F00", "#56B4E9"))+
theme_minimal()
# 手动设置填充色
f + geom_crossbar(aes(fill = dose)) +
scale_fill_manual(values = c("#999999", "#E69F00", "#56B4E9"))+
theme_minimal()
多个分组
df3 <- df %>%
group_by(supp, dose) %>%
summarise(
sd = sd(len),
len = mean(len)
)
head(df3)
f <- ggplot(df3, aes(x = dose, y = len,
ymin = len-sd, ymax = len+sd))
f + geom_crossbar(aes(color = supp))
# 使用 position_dodge()避免重叠
f + geom_crossbar(aes(color = supp),
position = position_dodge(1))
Error bar
f <- ggplot(df2, aes(x = dose, y = len))
f + geom_errorbar(aes(color = dose,ymin = len-sd, ymax = len+sd), width = 0.2)
# 加上连线
f + geom_line(aes(group = 1)) +geom_errorbar(aes(color = dose,ymin = len-sd, ymax = len+sd), width = 0.2)
# 加上柱子
f + geom_bar(aes(color = dose), stat = "identity", fill ="white") +
geom_errorbar(aes(color = dose,ymin = len-sd, ymax = len+sd), width = 0.2)
# 只保留上面一半的bar
f + geom_bar(aes(color = dose), stat="identity", fill ="white") +
geom_errorbar(aes(color = dose,ymin = len, ymax = len+sd), width = 0.2)
多重分组的Error bar
f <- ggplot(df3, aes(x = dose, y = len))
# 柱状图+Error bar
f +geom_errorbar(aes(color = supp,ymin = len-sd, ymax = len+sd),position = "dodge")+ geom_bar(aes(fill = supp), stat = "identity",
position = "dodge")
# 线图+Error bar
f + geom_line(aes(group = supp, color = supp)) +
geom_errorbar(aes(color = supp,ymin = len-sd, ymax = len+sd),width=0.2,position = position_dodge(0.05))+
geom_point(aes(color = supp))
以垂直线表示的间隔
f <- ggplot(df2, aes(x = dose, y = len,
ymin=len-sd, ymax=len+sd))
f + geom_linerange()
f + geom_pointrange()
点图与error bars 结合
g <- ggplot(df, aes(x=dose, y=len)) +
geom_dotplot(binaxis='y', stackdir='center')
# 用 geom_crossbar()
g + stat_summary(fun.data="mean_sdl", fun.args = list(mult=1),
geom="crossbar", width=0.5)
# 用 geom_errorbar()
g + stat_summary(fun.data=mean_sdl, fun.args = list(mult=1),
geom="errorbar", color="red", width=0.2) +
stat_summary(fun.y=mean, geom="point", color="red")
# 用 geom_pointrange()
g + stat_summary(fun.data=mean_sdl, fun.args = list(mult=1),
geom="pointrange", color="red")
单基因泛癌分析
TCGA单基因免疫相关泛癌分析(应要求,对出图添加更细致的描述)
资源贴
赞 (0)