本系列課程要求大家有一定的R語言基礎,對于完全零基礎的同學,建議去聽一下師兄的《生信必備技巧之——R語言基礎教程》。本課程將從最基本的繪圖開始講解,深入淺出的帶大家理解和運用強大而靈活的ggplot2包。內容包括如何利用ggplot2繪制散點圖、線圖、柱狀圖、添加注解、修改坐標軸和圖例等。
本次課程所用的配套書籍是:《R Graphic Cookbooks》
除了以上的基本圖形外,師兄還會給大家講解箱線圖、提琴圖、熱圖、火山圖、氣泡圖、?;鶊D、PCA圖等各種常用的生信圖形的繪制,還不趕緊加入收藏夾,跟著師兄慢慢學起來吧!
R語言繪圖練習02 -- 克利夫蘭點圖:
###########
# 柱狀圖拓展:克里夫蘭點圖繪制:
library(gcookbook)
tophit <- tophitters2001[1:25, ] # 取前25行;
# 從最基本的散點圖出發(fā)
ggplot(tophit, aes(x=avg, y=name))+
geom_point()

克利夫蘭點圖01
# reorder排序一定要熟練:前面柱狀圖排序講過:
ggplot(tophit, aes(x=avg, y=reorder(name, avg))) +
geom_point(size=3) + # 修改點的大小
theme_bw() + # 修改背景
theme(panel.grid.major.x=element_blank(), # 設置縱向網格線為空;
panel.grid.minor.x =element_blank(),
# 設置橫向網格線為虛線(dashed);
panel.grid.major.y =element_line(colour="grey60", linetype="dashed"))

克利夫蘭點圖02
# 顛倒圖形的x軸和y軸;
ggplot(tophit, aes(x=reorder(name,avg), y=avg)) +
geom_point(size=3) +
theme_bw() +
theme(axis.text.x= element_text(angle=60, hjust=1),
panel.grid.major.y=element_blank(),
panel.grid.minor.y =element_blank(),
panel.grid.major.x =element_line(colour="grey60", linetype="dashed"))

克利夫蘭點圖03
# 按照lg和avg對name進行排序,先按lg排,再按avg排;
nameorder <- tophit$name[order(tophit$lg, tophit$avg)]
# 將name變量轉換為因子,因子水平設定為nameorder;
tophit$name <- factor(tophit$name, levels=nameorder)
## 繪制彩色克利夫蘭點圖:
ggplot(tophit, aes(x=avg, y=name))+
geom_segment(aes(yend=name), xend=0, colour="grey50")+
geom_point(size=3, aes(colour=lg))+ # 設置分組變量;
# limits限定顏色先后順序;
scale_colour_brewer(palette="Set1", limits=c("NL", "AL"))+
theme_bw() +
theme(panel.grid.major.y =element_blank(), # 去除橫向網格線
legend.position=c(1, 0.55), # 設置圖例的位置:這里的1指的是與x軸的比例;
# legend.justification=c(1, 0.5)表示圖例右邊緣中點;
# (1,0)表示右下角,(0,1)表示左上角,以此類推;
legend.justification=c(1, 0.5))

克利夫蘭點圖04
# 分面繪制:facet_grid()函數:
ggplot(tophit, aes(x=avg, y=name))+
geom_segment(aes(yend=name), xend=0, colour="grey50")+
geom_point(size=3, aes(colour=lg))+
# guides去除圖例;
scale_colour_brewer(palette="Set1", limits=c("NL", "AL"),guide = F)+
theme_bw() +
theme(panel.grid.major.y = element_blank()) +
# 一列多行:lg~.;行數等于lg的種類數目;
# scales設置每個分塊的單位寬度;space設置每個分塊的寬度;
facet_grid(lg~., scales="free_y", space="free_y")

克利夫蘭點圖05
往期文章
- R語言繪圖(ggplot2、ggpubr)從入門到精通01--課程介紹
- R語言繪圖(ggplot2、ggpubr)從入門到精通02--柱狀圖和直方圖
- R語言繪圖(ggplot2、ggpubr)從入門到精通03--箱式圖和函數圖像
- R語言繪圖(ggplot2、ggpubr)從入門到精通04--柱狀圖美化之調色
- R語言繪圖(ggplot2、ggpubr)從入門到精通05--柱狀圖美化之分組修改
- R語言繪圖(ggplot2、ggpubr)從入門到精通06--柱狀圖美化之寬度調節(jié)
- R語言繪圖(ggplot2、ggpubr)從入門到精通07--柱狀圖美化之如何加標簽
- R語言繪圖練習01 -- 各種類型的餅圖