R语言初学

R语言绘图(ggplot2、ggpurb)从入门到精通06--柱

2021-05-30  本文已影响0人  生信师兄

本系列课程要求大家有一定的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")
上一篇下一篇

猜你喜欢

热点阅读