ggplot2绘图学习 Bar Plots
之前我们学习了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 Plots
主要函数及参数
· Key function: geom_bar()
· Key arguments to customize the plot: alpha, color, fill, linetype and size.
数据类型
library(ggplot2)
df <- data.frame(dose=c("D0.5", "D1", "D2"),
len=c(4.2, 10, 29.5))
head(df)
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
dose=rep(c("D0.5", "D1", "D2"),2),
len=c(6.8, 15, 33, 4.2, 10, 29.5))
head(df2)
f <- ggplot(df, aes(x = dose, y = len))
# 基础图形
f + geom_bar(stat = "identity")
# 改变填充色,并加上y轴数值 (vjust = -0.3)
f + geom_bar(stat = "identity", fill = "steelblue")+
geom_text(aes(label = len), vjust = -0.3, size = 3.5)+
theme_minimal()
# 把数值放到柱子里 vjust = 1.6
f + geom_bar(stat="identity", fill="steelblue")+
geom_text(aes(label=len), vjust=1.6, color="white", size=3.5)+
theme_minimal()
改变柱子的宽度和顺序
f + geom_bar(stat="identity", fill="steelblue",width =0.5)+
geom_text(aes(label=len), vjust=1.6, color="white", size=3.5)+
theme_minimal()+scale_x_discrete( limits=c("D2","D1","D0.5") )
分组配色
# 改变边框色
f + geom_bar(aes(color = dose), stat="identity", fill="white")
# 改变填充色
f + geom_bar(aes(fill = dose), stat="identity")
# 手动改变边框色
f + geom_bar(aes(color = dose), stat="identity", fill="white") +
scale_color_manual(values = c("#999999", "#E69F00", "#56B4E9"))
# 手动改变填充色
f + geom_bar(aes(fill = dose), stat="identity") +
scale_fill_manual(values = c("#999999", "#E69F00", "#56B4E9"))
多个分组
g <- ggplot(data=df2, aes(x=dose, y=len, fill=supp))
# 重叠在一起
p1<-g + geom_bar(stat = "identity")
# 各自分开
p2<-g + geom_bar(stat="identity", position=position_dodge())
p1+p2
分别添加数值
ggplot(data=df2, aes(x=dose, y=len, fill=supp)) +
geom_bar(stat="identity", position = position_dodge())+
geom_text(aes(label = len), vjust = 1.6, color = "white",
position = position_dodge(0.9), size = 3.5)
如何再堆积的柱子中添加数值呢?这里需要三步
1. 对数值进行排序
require(plyr)
# Sort by dose and supp
df_sorted <- arrange(df2, dose, supp)
head(df_sorted)
2. 分别计算Y轴数值的和
df_cumsum <- ddply(df_sorted, "dose", transform,
label_ypos=cumsum(len))
head(df_cumsum)
3. 画图
ggplot(data=df_cumsum, aes(x = dose, y = len, fill = supp)) +
geom_bar(stat = "identity")+
geom_text(aes(y = label_ypos, label = len), vjust=1.6,
color = "white", size = 3.5)
单基因泛癌分析
TCGA单基因免疫相关泛癌分析(应要求,对出图添加更细致的描述)
资源贴
赞 (0)