本系列課程要求大家有一定的R語言基礎,對于完全零基礎的同學,建議去聽一下師兄的《生信必備技巧之——R語言基礎教程》。本課程將從最基本的繪圖開始講解,深入淺出的帶大家理解和運用強大而靈活的ggplot2包。內容包括如何利用ggplot2繪制散點圖、線圖、柱狀圖、添加注解、修改坐標軸和圖例等。
本次課程所用的配套書籍是:《R Graphic Cookbooks》
除了以上的基本圖形外,師兄還會給大家講解箱線圖、提琴圖、熱圖、火山圖、氣泡圖、桑基圖、PCA圖等各種常用的生信圖形的繪制,還不趕緊加入收藏夾,跟著師兄慢慢學起來吧!
R語言繪圖練習01 -- 各種類型的餅圖
- 柱狀圖拓展--餅圖
################
library(ggplot2)
# 技巧篇--ggplot2繪制各種餅圖:
mpg <- mpg
# 把y軸方向扭曲了,柱子都變成了彎的:
ggplot(mpg, aes(class))+
geom_bar()+
coord_polar(theta = "y")
餅圖01
# 把x軸方向扭曲了,柱子都從同一個中心出發
ggplot(mpg, aes(class))+
geom_bar()+
coord_polar(theta = "x")
餅圖02
# 加上顏色分組:
ggplot(mpg, aes(class))+
geom_bar(aes(fill=drv))+
coord_polar(theta = "y")
餅圖03
# 加上顏色分組:
ggplot(mpg, aes(class))+
geom_bar(aes(fill=drv))+
coord_polar(theta = "x")
餅圖04
# 如何繪制正常的餅圖?
ggplot(mpg, aes(1, fill=class))+
geom_bar(width = 0.5)+
coord_polar(theta = "y")
# 加上標簽:
ggplot(mpg, aes(1, fill=class))+
geom_bar(width = 0.5)+
coord_polar(theta = "y")+
geom_text(stat="count",aes(label = scales::percent(..count../100)),
size=3, position=position_stack(vjust = 0.5))
餅圖05
########
# 課后作業:如何使用position_stack()修改標簽位置呢?
library(gcookbook)
library(plyr)
ce <- arrange(cabbage_exp, Date, Cultivar)
ce<-ddply(ce, "Date", transform, label_y=cumsum(Weight)-0.5*Weight)
ce$Cultivar <- factor(ce$Cultivar,levels = c("c52","c39"))
ggplot(ce, aes(x=Date, y=Weight, fill=Cultivar))+
geom_bar(stat="identity") +
geom_text(aes(y=label_y, label=Weight), vjust=1.5, colour="white")
# 使用position_stack()可以大大節約我們的代碼:
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar))+
geom_bar(stat="identity") +
geom_text(aes(label=Weight), position = position_stack(vjust=0.5), colour="white")