分享

如何用R画一个柱状图,代码都在这里了

 萌小芊 2018-03-23

画图是生物信息分析中的高频动作,在第二讲《错过她,也不能错过的R语言》中,我们留下一个彩蛋,今天来放送答案。


在统计学中,变量按变量值是否连续可分为连续变量与离散变量两种。


       柱状图一般用于离散变量绘图,那离散变量指的是什么呢?


小板报

离散变量是指其数值只能用自然数或整数单位计算的则为离散变量。

反之,在一定区间内可以任意取值的变量叫连续变量,其数值是连续不断的,相邻两个数值可作无限分割,即可取无限个数值。

 

在ggplot2中绘制柱状图使用的几何对象是geom_bar(),默认的统计变换是stat_count(对映射到x轴的变量计数),如果我们的数据不需要默认的计数统计变换,且已经做好统计变换,只需要直接绘图,设置参数geom_bar(stat='identity') 即可。


柱形图一般有3种形式,1)填充式;2)堆积式;3)并列式。


首先,我们模拟一个包括3列的数据,并赋值给data变量,用head(data)函数查看前6行,展示如下:

specie <- c(rep('sorgho'="" ,="" 3)="" ,="" rep('poacee'="" ,3)="" ,="" rep('banana'="" ,="" 3)="" ,="" rep('triticum'="" ,="" 3)="">

condition <- rep(c('normal'="" ,="" 'stress'="" ,'nitrogen')="" ,="">

value <- abs(rnorm(12="" ,="" 0="" ,="">

data <->

 

在绘图的时候把specie映射给x,value映射给y,condition映射给颜色属性。并且设置坐标轴标题字体16,坐标轴标签字体14,图片的title字体为20

 

1)填充式需要设定几何对象geom_bar()的参数position='fill'(堆叠数据,百分比展示)


p <- ggplot(data,="" aes(x="specie,"  y="value," fill="">

+geom_bar(stat='identity', position='fill'

+theme_bw()

+labs(x = 'Specie',y = 'Value', title = 'This is barplot') 

+theme(axis.title =element_text(size = 16),axis.text =element_text(size = 14, color = 'black'),plot.title =element_text(hjust = 0.5, size = 20))

p


2)堆积式需要设定几何对象geom_bar()的参数position = 'stack'(堆叠数据,非百分比展示)


p <- ggplot(data,="" aes(x="specie," y="value," fill="">

+geom_bar(stat='identity', position='stack'

+theme_bw() 

+labs(x = 'Specie',y = 'Value', title = 'This is barplot') 

+theme(axis.title =element_text(size = 16),axis.text =element_text(size = 14, color = 'black'),plot.title =element_text(hjust = 0.5, size = 20))

p

 

 

3)并列式需要设定几何对象geom_bar()的参数position= 'dodge'(并列数据,非百分比展示)


p <- ggplot(data,="" aes(x="specie," y="value," fill="">

+geom_bar(stat='identity', position='dodge'

+theme_bw() 

+labs(x = 'Specie',y = 'Value', title = 'This is barplot') 

+theme(axis.title =element_text(size = 16),axis.text =element_text(size = 14, color = 'black'),plot.title =element_text(hjust = 0.5, size = 20))

p


柱状图、散点图、饼图、热图、韦恩图、箱形图···


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约