本系列課程要求大家有一定的R語言基礎,對于完全零基礎的同學,建議去聽一下師兄的《生信必備技巧之——R語言基礎教程》。本課程將從最基本的繪圖開始講解,深入淺出的帶大家理解和運用強大而靈活的ggplot2包。內容包括如何利用ggplot2繪制散點圖、線圖、柱狀圖、添加注解、修改坐標軸和圖例等。
本次課程所用的配套書籍是:《R Graphic Cookbooks》
除了以上的基本圖形外,師兄還會給大家講解箱線圖、提琴圖、熱圖、火山圖、氣泡圖、桑基圖、PCA圖等各種常用的生信圖形的繪制,還不趕緊加入收藏夾,跟著師兄慢慢學起來吧!
第二章:柱狀圖深入探究
- 調整條形的寬度和間距:
#######################
## 調節條形的寬度和間距(width參數):
Library(cookbook)
# width默認是0.9;
ggplot(pg_mean, aes(x=group, y=weight)) +
geom_bar(stat="identity")
ggplot(pg_mean, aes(x=group, y=weight)) +
geom_bar(stat="identity", width=0.5)
# width最大值只能設置為1;
ggplot(pg_mean, aes(x=group, y=weight)) +
geom_bar(stat="identity", width=1)
## 調節分組條形圖之間的間距:
# 默認的同一分組之間的條形是沒有間距的:
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar))+
geom_bar(stat ="identity", width=0.5, position= "dodge")
# 只需要將position_dodge參數設置的比width參數大一些就好了!
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat="identity", width=0.5, position = position_dodge(0.7))
# 思考:position_dodge有什么含義?為什么比width大就會有間隙?
# 因為默認的position_dodge()里的內容一定是和width相等的,
# 當position_dodge為0的時候,兩個柱子會重合;
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat="identity", width=0.5, position = position_dodge(0.3))
- 堆積柱狀圖拓展:
#######################
## 堆積柱狀圖:
# position的默認值為stack;
# 即如果不設置position,并且設置了分組變量,就是畫堆積圖;
Library(cookbook)# For the data set
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat="identity")
# 修改圖例堆積的順序:guides()
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat="identity") +
guides(fill = guide_legend(reverse = TRUE))
# 修改圖形堆積的順序:order = desc(); desc()可以簡單地理解為取相反數;
cabbage_exp$Cultivar <- factor(cabbage_exp$Cultivar,levels = c("c39","c52"))
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat="identity")
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat="identity", color = "black") +
guides(fill = guide_legend(reverse = TRUE)) +
scale_fill_brewer(palette = "Pastel1")