R语言绘图从入门到精通07--柱状图美化之如何加标签
2021-06-07 本文已影响0人
生信师兄
本系列课程要求大家有一定的R语言基础,对于完全零基础的同学,建议去听一下师兄的《生信必备技巧之——R语言基础教程》。本课程将从最基本的绘图开始讲解,深入浅出的带大家理解和运用强大而灵活的ggplot2包。内容包括如何利用ggplot2绘制散点图、线图、柱状图、添加注解、修改坐标轴和图例等。
本次课程所用的配套书籍是:《R Graphic Cookbooks》
除了以上的基本图形外,师兄还会给大家讲解箱线图、提琴图、热图、火山图、气泡图、桑基图、PCA图等各种常用的生信图形的绘制,还不赶紧加入收藏夹,跟着师兄慢慢学起来吧!
第二章:柱状图深入探究
- 柱状图加标签:
# 添加标签:
library(ggplot2)
library(gcookbook)
cabbage_exp <- cabbage_exp
# 标签位置的设定:vjust参数;
ggplot(cabbage_exp, aes(x=interaction(Date, Cultivar), y=Weight)) +
geom_bar(stat="identity") +
geom_text(aes(label=Weight), vjust=1.5, colour="white")
加标签01
ggplot(cabbage_exp, aes(x=interaction(Date, Cultivar), y=Weight)) +
geom_bar(stat="identity") +
geom_text(aes(label = Weight), vjust=-0.2)
# 为了防止标签跑出图形,可以调整y轴的范围:
# 方法一:ylim()函数:
ggplot(cabbage_exp, aes(x=interaction(Date, Cultivar), y=Weight)) +
geom_bar(stat="identity") +
geom_text(aes(label=Weight), vjust=-0.2) +
ylim(0, max(cabbage_exp$Weight)* 1.05)
# 方法二:以weight为基准,调节y值,图形高度会自动适配:
ggplot(cabbage_exp, aes(x=interaction(Date, Cultivar), y=Weight))+
geom_bar(stat="identity")+
geom_text(aes(y = Weight + 0.1, label = Weight))
加标签02
# 分组柱状图加标签:需要设定position_dodge(),以调整字体的合适位置;
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar))+
geom_bar(stat = "identity", position = "dodge") +
geom_text(aes(label=Weight), vjust=1.5, color="white",
position=position_dodge(.9), size=3)
加标签03
library(plyr)
# 堆积柱状图添加lable
ce <- arrange(cabbage_exp, Date, Cultivar)
ce<-ddply(ce, "Date", transform, label_y=cumsum(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")
# 修改lable至中央:
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")
加标签04
# 添加单位,并修改颜色模式
ggplot(ce, aes(x=Date, y=Weight, fill=Cultivar))+
geom_bar(stat="identity", colour="black")+
geom_text(aes(y=label_y, label=paste(format(Weight, nsmall=2), "kg")),size=4)+
scale_fill_brewer(palette="Pastel1")
加标签05