之前我們學習了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.6f + 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)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單基因免疫相關泛癌分析(應要求,對出圖添加更細緻的描述)
TCGA單基因免疫相關泛癌分析-進階版本
資源貼
生信小課堂資源匯總