R语言之ggplot

Python012

R语言之ggplot,第1张

ggplot2的核心理念是将绘图与数据分离,数据相关的绘图与数据无关的绘图分离。按图层作图,保有命令式作图的调整函数,使其更具灵活性,并将常见的统计变换融入到了绘图中。

ggplot的绘图有以下几个特点:第一,有明确的起始(以ggplot函数开始)与终止(一句语句一幅图);其二,图层之间的叠加是靠“+”号实现的,越后面其图层越高。

ggplot2里的所有函数可以分为以下几类:

一个图形对象就是一个包含数据,映射,图层,标度,坐标和分面的列表,外加组件options

ggplot(数据, 映射) geom_xxx(映射, 数据) stat_xxx(映射, 数据)

点(point, text):往往只有x、y指定位置,有shape但没有fill

线(line,vline,abline,hline,stat_function等):一般是基于函数来处理位置

射(segment):特征是指定位置有xend和yend,表示射线方向

面(tile, rect):这类一般有xmax,xmin,ymax,ymin指定位置

棒(boxplot,bin,bar,histogram):往往是二维或一维变量,具有width属性

带(ribbon,smooth):透明是特征是透明的fill

补:包括rug图,误差棒(errorbar,errorbarh)

然后,就是按照你的需要一步步加图层了(使用“+”)。

给你一些代码,你慢慢研究:install.packages('ggplot2')library(ggplot2)ggplot(a)+geom_bar(aes(x1,y,fill/col=x1/x2),position='dodge',stat='summary',fun='sum'/'mean')条形图+theme(text = element_text(family='Kai'))ggplot(a)+geom_boxplot(aes(x1,y,col=x1/x2))箱线图ggplot(a)+geom_point(aes(x1,y,col=x1/x2),position=position_jitter(width=0.04))散点图1+geom_point(aes(x1,y,col=x1/x2),stat='summary',fun='sum'/'mean')+散点2+geom_line(aes(x1,y,group=1/x2,col=x1/x2),stat='summary',fun='sum'/'mean')+折线3+geom_errorbar(aes(x=x1,ymin=y-se,ymax=y+se,col=x1/x2),position=position_dodge(0.9),width=0.2)+误差棒4+geom_text(aes(x1,y,label=marker,col=x1/x2),position=position_dodge(0.9)vjust=2或y+2)+显著字母ggplot(a,aes(x1,y,fill/col=x1/x2))+geom_bar(position='dodge',stat='summary',fun='sum'/'mean')+geom_errorbar(aes(ymin=y-se,ymax=y+se),position=position_dodge(0.9),width=0.2)+geom_text(aes(label=marker),position=position_dodge(0.9),vjust=-2)条形图+误差棒+显著字母(坐标写一次即可)ggplot(a,aes(x1,y,col=x1/x2))+geom_point(position=position_jitter(width=0.04),stat='summary',fun='sum'/'mean')+geom_line(aes(group=1/x2),stat='summary',fun='sum'/'mean')+geom_errorbar(aes(ymin=y-se,ymax=y+se),position=position_dodge(0.9),width=0.2)+geom_text(aes(label=marker),position=position_dodge(0.9),vjust=-2)散点图+折线+误差棒+显著字母(坐标写一次即可)+geom_density(aes(y=liqi))密度图(1个数值型)+geom_area(aes(x=tan,y=liqi))区域图(2个数值型)+geom_smooth(aes(x=tan,y=liqi,group/col=chong),formula=y~x,method='lm',se=F)拟合图,分组/线条颜色(2个数值型)+facet_wrap(~riqi,ncol/nrow=2,labeller='label_both/value')分面图,每行或每列分面数,分面标题+xlab('自变量1(单位)')+ylab('因变量(单位)')+scale_fill_discrete(name='自变量2')更改轴和图例名称+coord_cartesian(ylim= c(0,80))限定轴范围(fill=x1/x2,有此即可变色)+scale_fill_manual(values = c('grey70', 'grey50', 'grey30'))改变条形填充颜色(颜色数量=分组数量)(col=x1/x2,有此即可变色)+scale_color_manual(values = c('red', 'orange', 'yellow'))改变颜色(颜色数量=分组数量)