-
2020-11-22 02:21:45
这次给大家带来的是R语言绘图神器—ggplot2绘图包,根据Hadley的说法,这个包的核心思想,是来源于 Leland Wilkinson《The Grammar of Graphics》。Hadley在他的书中建议大家都去读一读这本书,以便对ggplot2的绘图思想有一个了解。我读了这本书的一小部分,发现这本书理解起来还是比较困难的。
我在学习ggplot2绘图主要是通过《R Graphics Cookbook》这本书,这本书目前出到了第二本,网上也有它的电子版本可供免费阅读,链接如下:
https://r-graphics.org/
简单的说呢,ggplot2的绘图方式可以理解为元素映射和图像叠加。
元素映射是指数据和图像之间的对应关系、图像中图形和其属性(大小、颜色、透明度、形状)的对应关系以及图形和图例的对应关系。
图像叠加就是图像中的坐标轴、背景主题、图形元素(组)、图例等图形的透视叠加,这个是遵循透视法则的。比如最新的图形会叠加在原有的图形之上,可能会对原有图形造成遮挡,也可能和原有图形共同组成一幅新的图形,需要使用代码定义设置。
在ggplot2输出的图形中,坐标轴、图形元素、图例、标题、文本、背景主题等等,都是可以自定义编辑设置的,这就给了创作者很大的发挥空间,能够根据自己的需要绘制精美的图形。
对于ggplot2的学习,虽然我已经掌握了基本的绘图方法,但还有更多内容需要在实践中进一步学习才行,以下是我的读书笔记。
#R Graphic CookBooK 笔记(ggplot2)library(ggplot2)library(gcookbook)library(data.table)library(MASS)#2.1散点图Scartter Plotggplot(data=mtcars,aes(x=wt,y=mpg)) + geom_point()#2.2折线图Line Graphggplot(pressure,aes(x=temperature,y=pressure)) + geom_line() + geom_point()#2.3条形图Bar Graphggplot(BOD,aes(x=Time,y=demand)) + geom_col()ggplot(BOD,aes(x=factor(Time),y=demand)) + geom_col()#2.4直方图Histogramggplot(mtcars,aes(x=mpg)) + geom_histogram(binwidth = 4)#2.5箱型图Box Plotggplot(ToothGrowth,aes(x=supp,y=len)) + geom_boxplot()#2.6绘制函数曲线Function Curvemyfun x){ggplot(data.frame(x=c(-10,10)),aes(x)) + stat_function(fun=myfun,geom = "line")#3.条形图#3.2分组作图ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar)) + geom_col(position = "dodge",color="black") + scale_fill_brewer(palette = "Pastel1")#3.4给条形图上色upc 1:ggplot(upc,aes(x=Abb,y=Change,fill=Region))+geom_col(color="Black")ggplot(upc,aes(x=reorder(Abb,Change),y=Change,fill=Region)) + geom_col(color="Black") + scale_fill_manual(values = c("#669933","#FFCC66")) + xlab("State")#3.5分正负号作图和上色climate_sub "Berkeley"&Year >= ggplot(climate_sub,aes(x=Year,y=Anomaly10y,fill=Pos)) + geom_col(position = "Identity",color="Black",size=0.1) + scale_fill_manual(values=c("#CCEEFF","#FFDDDD"),guide=FALSE)#3.6调整宽度和间距ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar)) + geom_col(width=0.5,position = position_dodge(0.7))#3.7堆叠型条形图(可以看单条的百分比)ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar)) + geom_col() + guides(fill=guide_legend(reverse = TRUE))#3.8百分比堆叠型条形图ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar)) + geom_col(color="Black",position = "fill") + scale_y_continuous(labels=scales::percent) + scale_fill_brewer(palette = "Pastel1")#3.9给条形图加标签ggplot(cabbage_exp,aes(x=interaction(Date,Cultivar),y=Weight)) + geom_col() + geom_text(aes(label = Weight),vjust=1.5,color="White")ggplot(mtcars,aes(x=factor(cyl))) + geom_bar() + geom_text(aes(label=..count..),stat="count",vjust=1.5,color="white")ggplot(cabbage_exp,aes(x=interaction(Date,Cultivar),y=Weight)) + geom_col() + geom_text(aes(label=Weight),vjust=-0.2) + ylim(0,max(cabbage_exp$Weight)*1.15)ggplot(cabbage_exp,aes(x=interaction(Date,Cultivar),y=Weight)) + geom_col() + geom_text(aes(y=Weight - 0.2,label=Weight))ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar)) + geom_col(position="dodge") + geom_text(aes(label=Weight),color="white",vjust=1.5,position = position_dodge(.9))#3.10制作克利夫兰点图tophit 1: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(),panel.grid.major.y = element_line(color = "grey60",linetype = "dashed"))ggplot(tophit,aes(x=reorder(name,avg),y=avg)) + geom_point(size=3) + theme_bw() + theme(panel.grid.major.y = element_blank(),panel.grid.minor.y = element_blank(),panel.grid.major.x = element_line(color = "grey60",linetype = "dashed"),axis.text.x = element_text(angle = 60,hjust = 1))#4折线图 Line Graphs#4.1基本折线图ggplot(BOD,aes(x=Time,y=demand)) + geom_line()#4.2将点加入折线图中ggplot(BOD,aes(x=Time,y=demand)) + geom_line() + geom_point()ggplot(worldpop,aes(x=Year,y=Population)) + geom_line() + geom_point()#4.3多个折现的折线图ggplot(tg,aes(x=dose,y=length,color=supp)) + geom_line()ggplot(tg,aes(x=dose,y=length,linetype=supp,color=supp)) + geom_line() + geom_point(shape=21)#4.4更改线条的外观ggplot(BOD,aes(x=Time,y=demand)) + geom_line(linetype="dashed",size=1,color="blue")ggplot(tg,aes(x=dose,y=length,color=supp)) + geom_line() + scale_color_brewer(palette = "Set1")ggplot(tg,aes(x=dose,y=length,group=supp)) + geom_line(color="darkblue",size=1.5)ggplot(tg,aes(x=dose,y=length,color=supp)) + theme_bw() + geom_line(linetype="dashed") + geom_point(shape=22,size=3,fill="white")#4.5改变点的外观pd 0.ggplot(tg,aes(x=dose,y=length,fill=supp)) + geom_line(position=pd) + geom_point(shape=21,size=3,position=pd) + scale_fill_manual(values = c("Black","White"))#4.6制作阴影图sunspotyear time(sunspot.year)),Sunspots=as.numeric(sunspot.year))ggplot(sunspotyear,aes(x=Year,y=Sunspots)) + geom_area()ggplot(sunspotyear,aes(x=Year,y=Sunspots)) + theme_bw() + geom_area(color="black",fill="blue",alpha=.2)ggplot(sunspotyear,aes(x=Year,y=Sunspots)) + theme_bw() + geom_area(fill="blue",alpha=.2) + geom_line()#4.7制作堆叠面积图ggplot(uspopage,aes(x=Year,y=Thousands,fill=AgeGroup)) + theme_bw() + geom_area()ggplot(uspopage,aes(x=Year,y=Thousands,fill=AgeGroup)) + theme_bw() + geom_area(alpha=.4) + scale_fill_brewer(palette = "Blues") + geom_line(position = "stack",size=.2)#4.8制作带比例的堆叠面积图ggplot(uspopage,aes(x=Year,y=Thousands,fill=AgeGroup)) + theme_bw() + geom_area(position = "fill",color="black",size=.2,alpha=.4) + scale_fill_brewer(palette = "Blues") + scale_y_continuous(labels=scales::percent)#4.9添加置信区间climate_mod "Berkeley",.(Year,Anomaly10y,Unc10y)]ggplot(climate_mod,aes(x=Year,y=Anomaly10y)) + geom_ribbon(aes(ymin=Anomaly10y-Unc10y,ymax=Anomaly10y+Unc10y),alpha=.2) + geom_line()ggplot(climate_mod,aes(x=Year,y=Anomaly10y)) + geom_line(aes(y=Anomaly10y-Unc10y),color="grey50",linetype="dotted") + geom_line(aes(y=Anomaly10y+Unc10y),color="grey50",linetype="dotted") + geom_line()#5.散点图#5.1制作基本散点图HW ggplot(HW,aes(x=ageYear,y=heightIn)) + geom_point(shape=21,size=1.5)#5.2按数据标签进行分组HW1 ggplot(HW1,aes(x=ageYear,y=heightIn,shape=sex,color=sex)) + geom_point()ggplot(HW1,aes(x=ageYear,y=heightIn,shape=sex,color=sex)) + geom_point() + scale_shape_manual(values = c(1,2)) + scale_color_brewer(palette="Set1")#5.3使用不同形状的点ggplot(HW1,aes(x=ageYear,y=heightIn,shape=sex,color=sex)) + geom_point(shape=5)#5.4为连续变量设置颜色或大小HW2 ggplot(HW2,aes(x=ageYear,y=heightIn,color=weightLb)) + geom_point()ggplot(HW2,aes(x=ageYear,y=heightIn,size=weightLb)) + geom_point()ggplot(HW2,aes(x=ageYear,y=heightIn,size=weightLb)) + geom_point() + scale_size_area()#5.5处理过多点绘图问题diamonds_sp x=carat,diamonds_sp + stat_bin2d(bins=50) + scale_fill_gradient(low="lightblue",high = "red",limits=c(0,6000))CW_SP x=Time,CW_SP + geom_point(position = position_jitter(width=.5,height=0))CW_SP + geom_boxplot(aes(group=Time))#5.6添加拟合回归线hw_sp x=ageYear,hw_sp + geom_point(color="lightblue") + stat_smooth(method = lm,color="black")#5.7为自定义回归模型绘制拟合线#5.8从多个模型添加拟合线#5.9添加具有模型系数的注释#5.10为散点图添加边缘地毯(Marginal Rugs)#5.11为散点图中的点加标签(注释)countries_sub 2009 &healthexp > countries_sp x=healthexp,countries_sp + annotate("text",x=4350,y=5.4,label="Canada") + annotate("text",x=7400,y=6.8,label="USA")countries_sp + geom_text(aes(label=Name),size=4)#5.12创建气球图countrylist "Canada",cdat 2009&Name %in% countrylist]cdat_sp x=healthexp,cdat_sp + scale_size_area(max_size = 15)#5.13制作散点图矩阵c2009 2009,.(Name,GDP,laborrate,healthexp,infmortality)]pairs(c2009[,.(GDP,laborrate,healthexp,infmortality)])#6.汇总数据分布#6.1制作基本直方图ggplot(faithful,aes(x=waiting)) + geom_histogram(binwidth = 5,fill="white",color="black")binsize 15ggplot(faithful,aes(x=waiting)) + geom_histogram(binwidth = binsize,fill="white",color="black",boundary=47)#6.2使用分组数据制作多个直方图ggplot(birthwt,aes(x=bwt)) + geom_histogram(fill="white",color="black") + facet_grid(smoke~.)#6.3制作密度曲线ggplot(faithful,aes(x=waiting)) + geom_density()ggplot(faithful,aes(x=waiting)) + geom_line(stat="density") + expand_limits(y=0)#6.4使用分组数据制作多个直方图birthwt_mod "smoke":=as.factor(smoke)]ggplot(birthwt_mod,aes(bwt,fill=smoke)) + geom_density(alpha=.3)#6.5制作频率多边形图ggplot(faithful,aes(waiting)) + geom_freqpoly(binwidth=4)#6.6制作基本箱形图ggplot(birthwt,aes(x=factor(race),y=bwt)) + geom_boxplot(width=.5,outlier.size = 1.5,outlier.shape = 21)#6.7为箱型图添加切口ggplot(birthwt,aes(x=factor(race),y=bwt)) + geom_boxplot(notch = TRUE)#6.8在箱型图中添加均值ggplot(birthwt, aes(x = factor(race), y = bwt)) + geom_boxplot() + stat_summary(fun.y = "mean", geom = "point", shape = 23, size = 3, fill = "white")#6.9制作小提琴图#6.10绘制Wilkinson dot图:类似频率图c2009 2009&healthexp>ggplot(c2009,aes(infmortality)) + geom_dotplot()#6.11为分组数据绘制Wilkinson dot图#6.12制作二维分布的密度图faithful_p x=eruptions,faithful_p + geom_point() + stat_density2d(aes(color=..level..))faithful_p + stat_density2d(aes(fill=..density..),geom = "raster",contour = FALSE)faithful_p + geom_point() + stat_density2d(aes(alpha=..density..),geom = "tile",contour = FALSE)#7.注释Annotations#7.1添加文本注释p x=eruptions,p + annotate(geom = "text",x=3,y=48,label="Group1",family="serif",fontface="italic",color="darkred",size=3)#7.2在注释中使用数学公式p x=c(-p + annotate("text",x=2,y=0.3,parse=TRUE,label="frac(1,sqrt(2*pi))*e^{-x^2/2}")p + annotate("text",x=0,y=0.05,parse=TRUE,size=4,label="'Function: '* y==frac(1,sqrt(2*pi))*e^{-x^2/2}")#7.3添加线hw_plot x=ageYear,hw_plot + geom_hline(yintercept = 60) + geom_vline(xintercept = 14)hw_plot + geom_abline(intercept = 37.4,slope=1.75)hw_means "heightIn"=mean(heightIn)),keyby=sex]hw_plot + geom_hline(data=hw_means,aes(yintercept=heightIn,color=sex),linetype="dashed",size=1)#7.4添加线段和箭头p "Berkeley"],aes(p + annotate("segment",x=1950,xend=1980,y=-0.25,yend=-0.25)p + annotate(geom="segment",x=1850,xend=1820,y=-0.8,yend=-0.95,color="blue",size=2,arrow=arrow()) + annotate("segment",x=1950,xend=1980,y=-0.25,yend=-.25,arrow=arrow(ends="both",angle=90,length=unit(0.3,"cm")))#7.5添加阴影区域p + annotate("rect",xmin=1950,xmax=1980,ymin=-1,ymax=1,alpha=0.1,fill="blue")#7.6突出显示项目pg_mod "hl":=fifelse(group==ggplot(pg_mod,aes(x=group,y=weight,fill=hl)) + geom_boxplot() + scale_fill_manual(values=c("grey85","#FFDDCC"),guide=FALSE)#7.7添加错误条ce_mod "c39"]ggplot(ce_mod,aes(x=Date,y=Weight)) + geom_col(fill="white",color="black") + geom_errorbar(aes(ymin=Weight-se,ymax=Weight+se),width=0.2)ggplot(ce_mod,aes(x=Date,y=Weight)) + geom_line(aes(group=1)) + geom_point(size=4) + geom_errorbar(aes(ymin=Weight-se,ymax=Weight+se),width=0.2)ggplot(cabbage_exp,aes(x=Date,y=Weight,fill=Cultivar)) + geom_col(position="dodge") + geom_errorbar(aes(min=Weight-se,ymax=Weight+se),position=position_dodge(0.9),width=0.2)pd 0.ggplot(cabbage_exp,aes(x=Date,y=Weight,color=Cultivar,group=Cultivar)) + geom_errorbar(aes(ymin=Weight-se,ymax=Weight+se),width=0.2,size=0.25,color="black",position=pd) + geom_line(position=pd) + geom_point(position=pd,size=2.5)#7.8给各个分面加注释mpg_plot x=displ,f_labels "4",mpg_plot + geom_text(x=6,y=40,aes(label=label),data=f_labels)mpg_plot + annotate("text",x=6,y=42,label="label text")#8.坐标轴#8.1交换X轴和Y轴ggplot(PlantGrowth,aes(x=group,y=weight)) + geom_boxplot() + coord_flip()#8.2设定连续轴的范围pg_plot x=group,pg_plot + ylim(0,max(PlantGrowth$weight))#8.3翻转连续轴(切换正序方向)ggplot(PlantGrowth,aes(x=group,y=weight)) + geom_boxplot() + scale_y_reverse()ggplot(PlantGrowth,aes(x=group,y=weight)) + geom_boxplot() + ylim(6.5,3.5)#8.4改变分类变量在轴上的顺序pg_plot + scale_x_discrete(limits=c("ctrl","trt2"))#8.5设置X,Y轴的缩放比例m_plot x=Half,m_plot + coord_fixed() + scale_y_continuous(breaks=seq(0,420,30)) + scale_x_continuous(breaks=seq(0,420,30))#8.6设置刻度线的位置ggplot(PlantGrowth,aes(x=group,y=weight)) + geom_boxplot() + scale_y_continuous(breaks=c(4,4.25,4.5,5,6,8))#8.7删除刻度线和标签pg_plot + theme(axis.text.y=element_blank())pg_plot + theme(axis.ticks=element_blank(),axis.text.y=element_blank())pg_plot + scale_y_continuous(breaks=NULL)#8.8改变刻度标签的文本值hw_plot x=ageYear,hw_plot + scale_y_continuous(breaks=c(50,56,60,66,72),labels=c("Tiny","Really\nshort","Short","Medium","Tallish"))#8.9改变刻度标签的外观pg_plot + scale_x_discrete(breaks=c("ctrl","trt1","trt2"),labels=c("Control","Treatment 1","Treatment 2")) + theme(axis.text.x=element_text(angle=90,hjust=1,vjust=1))#8.10更改轴标签的文本hw_plot x=ageYear,hw_plot + xlab("Age in years") + ylab("Height in inches")hw_plot + labs(x="Age in years",y="Height in inches")hw_plot + scale_x_continuous(name="Age in years") + scale_y_continuous(name="Height in inches")#8.11删除轴标签pg_plot + xlab(NULL)#8.12改变轴标签的外观hw_plot + theme(axis.title.x=element_text(face="italic",color="darkred",size=14))hw_plot + ylab("Height\n(inches)") + theme(axis.title.y=element_text(angle=0,face="italic",size=14))#8.13显示轴线(颜色、粗细,线形)hw_plot + theme(axis.line=element_line(color="black"))#8.14使用对数轴animals_plot x=body,animals_plot + scale_x_log10() + scale_y_log10()#8.15为对数轴添加刻度#8.16绘制雷达图ggplot(wind,aes(x=DirCat,fill=SpeedCat)) + geom_histogram(binwidth=15,boundary=-7.5) + coord_polar() + scale_x_continuous(limits=c(0,360))#8.17在轴上使用日期#8.18在轴上使用相对时间#9.控制图形的整体外观#9.1设置图标题hw_plot x=ageYear,hw_plot + ggtitle("Age and Height of Schoolchildren","——11.5 to 17.5 years old")#9.2改变文本的外观hw_plot x=ageYear,hw_plot + theme(axis.title.x=element_text(size=0.9,lineheight=0.9,family="Microsoft YaHei",face="bold.italic",color="red"))hw_plot + ggtitle("这是图标题") + theme(plot.title=element_text(size=rel(1.5),lineheight=0.9,family="Microsoft YaHei"))#9.3使用主题hw_plot x=ageYear,hw_plot + theme_classic()#9.4改变主题的外观hw_plot x=ageYear,hw_plot + theme( panel.grid.major = element_line(color="red"), panel.grid.minor = element_line(color="red",linetype = "dashed",size=0.2), panel.background = element_rect(fill="lightblue"), panel.border = element_rect(color="blue",fill=NA,size=2) )hw_plot + theme( legend.background = element_rect(fill="grey85",color="red"), panel.grid.minor = element_line(color="red") )hw_plot + ggtitle("Plot title here") + theme(axis.title.x=element_text(color="red",size=14),axis.text.x=element_text(color="blue"),axis.title.y=element_text(color="red",size=14,angle=90),axis.text.y=element_text(color="blue"),plot.title=element_text(color="red",size=20,face="bold"))#9.5创造你自己的主题mytheme "red"), axis.title = element_text(size = rel(1.25)))hw_plot x=ageYear,#9.6隐藏网格线hw_plot x=ageYear,hw_plot + theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank())hw_plot + theme(panel.grid.major.x = element_blank(),panel.grid.minor.x = element_blank())#10.图例Legends#10.移除图例pg_plot x=group,pg_plot + guides(fill=FALSE)pg_plot + scale_fill_discrete(guide=FALSE)pg_plot + theme(legend.position = "none")#10.2改变图例的位置pg_plot x=group,pg_plot + theme(legend.position = "bottom")pg_plot + theme(legend.position = c(1,0),legend.justification = c(1,0))pg_plot + theme(legend.position = c(0.85,0.2),legend.background = element_rect(fill="white",color="black"))pg_plot + theme(legend.position = c(0.85,0.2)) + theme(legend.background = element_rect(fill="white",color="black"))pg_plot + theme(legend.position = c(0.85,0.2)) + theme(legend.background = element_blank()) + theme(legend.key = element_blank())#10.3改变图例的中组件的顺序pg_plot + scale_fill_discrete(limits=c("trt1","trt2","ctrl"))pg_plot + scale_fill_grey(start=.5,end=1,limits=c("trt1","trt2","ctrl"))pg_plot + scale_fill_brewer(palette="Pastel2",limits=c("trt1","trt2","ctrl"))#10.4将图例中的组件逆序pg_plot + guides(fill=guide_legend(reverse=TRUE))#10.5改变图例标题pg_plot x=group,pg_plot + labs(fill="Condition")pg_plot + scale_fill_discrete(name="Condition")hw_plot geom_point(aes(size=weightLb)) + scale_size_continuous(range=c(1,4))hw_plot + labs(color="Male/Female",size="Weight\n(pounds)")hw_plot2 x=ageYear,hw_plot2 + labs(shape="Male/Female",color="Male/Female")#10.6改变图例标题的外观pg_plot x=group, geom_boxplot()pg_plot + theme(legend.title = element_text( face = "italic", family = "Times", color = "red", size = 14))#10.7删除图例标题ggplot(PlantGrowth,aes(group,weight,fill=group)) + geom_boxplot() + guides(fill=guide_legend(title=NULL))#10.8改变标签中的文本pg_plot geom_boxplot()pg_plot + scale_fill_discrete(labels=c("Control","Treatment1","Treatment2"))#10.9-10.10更改图例文本的外观(字体、颜色、大小,文本多行)pg_plot + scale_fill_discrete(labels=c("Control","Type 1\nTreatment","Type 2\nTreatment")) + theme(legend.text = element_text(lineheight=.8),legend.key.height=unit(1,"cm"))#11.分集(切片)#11.1利用分集将数据切分成子图mpg_plot mpg_plot + facet_grid(drv~.)mpg_plot + facet_grid(.~cyl)mpg_plot + facet_grid(drv~cyl)mpg_plot + facet_wrap(~class)#11.2使用不同的轴进行分集mpg_plot + facet_grid(drv~cyl,scales = "free_y")#11.3修改分集标签的文本#11.4修改分集标签的外观和标题#12.在图中使用颜色#12.1设置对象的颜色ggplot(birthwt,aes(bwt)) + geom_histogram(fill="red",color="black")ggplot(mtcars,aes(wt,mpg)) + geom_point(color="red")#12.2用颜色表示变量ggplot(cabbage_exp,aes(Date,Weight,fill=Cultivar)) + geom_col(color="black",position="dodge")#12.3使用对色盲友好的调色板#12.4对离散变量使用不同的调色板#12.5对离散变量使用自定义调色板#12.6根据值来对阴影区域上色#13.其他图形#14.图形输出格式(PDF等等)#15.数据处理(dplyr)#附录
更多相关内容 -
8. R语言ggplot2-主成分分析PCA加置信圈.pdf
2021-11-10 11:16:558. R语言ggplot2-主成分分析PCA加置信圈.pdf -
21. R语言ggplot2—Y轴截断(break)绘图详解.pdf
2021-11-27 15:36:02当Y轴上的值差异性比较大的时候,如何进行坐标轴的截断,文档系统讲解了截断方法。 -
29.R语言ggplot2——点图、折线图绘制方法教程.pdf
2021-12-10 12:53:2929.R语言ggplot2——点图、折线图绘制方法教程.pdf -
R语言ggplot2柱状图(条形图)、簇状、并列、百分比绘图方法总结
2021-11-01 20:12:31最全的条形图绘制方法总结,毕业论文绘图必须教程,方便快捷解决你的绘图困扰 -
32.R语言ggplot2和ggtext实现条形图加文本标注教程.pdf
2021-12-20 13:18:0532.R语言ggplot2和ggtext实现条形图加文本标注教程.pdf -
R语言ggplot2基础绘图案例
2021-06-26 03:18:16R语言ggplot2基础绘图案例 内含 1.条形图两张(详细代码及png图) 2.散点图三张(详细代码及png图) 3.折线图两张(详细代码及png图) -
22. R语言—ggplot2_线形参数geom_line大全.pdf
2021-11-27 15:37:41不仅包含了传统的线形,同时进行拓展不同的线形 -
17. R语言ggplot2—使用箱型组合图表示数据分布方法汇总(箱型图、点图、提琴图、盒型图).pdf
2021-11-15 14:27:55汇总了目前论文发表中主要的箱型组合图使用方法,让论文秒变高大上的神器 -
R语言:R语言ggplot2的安装过程。
2021-12-19 21:01:06一、R语言的安装。 1.在搜索引擎中输入网址:R: The R Project for Statistical Computing (r-project.org)R: The R Project for Statistical Computing (r-project.org),跳转到R语言官网。 R: The R Project for...一、R语言的安装。
1.在搜索引擎中输入网址:R: The R Project for Statistical Computing (r-project.org)R: The R Project for Statistical Computing (r-project.org),跳转到R语言官网。
R: The R Project for Statistical Computing (r-project.org)
2. 点击download R,跳转结果如下:
3.选择China镜像,这里推荐使用中国科学技术大学的镜像,地址为:The Comprehensive R Archive Network。点击链接,得到以下界面,点击Download R for Windows。
4.点击后得到以下界面,点击install R for first time。
5.点击后,选折下载最新版本的R。
6.点击Download R 4.1.2 for Windows ,进行下载,安装。
二、RStudio的安装。
1.在搜索引擎输入网址RStudio | Open source & professional software for data science teams - RStudio,跳转到如下页面。
2.点击Products,如下图,然后点击Rstudio。
3.跳转后,选择Rstudio Desktop,跳转下一页。
4.点击DOWNLOAD RSTUDIO DESKTOP进行跳转。
5.跳转后选择Download RStudio Desktop的最新版本下载,下载成功。
三、R语言与RStudio下载成功后打开RStudio,如下图。
四、ggplot2的下载与调用。
1.首次使用在代码框中输入:install.packages(“ggplot2”),然后会自动下载成功。(注意同时下载时R语言和RStudio均选最新版本,否则会造成R语言和RStudio不兼容而下载失败)
2.选中install.packages(“ggplot2”),点击run运行,ggplot2安装成功。
3.以后使用ggplot2之前输入代码library(“ggplot2”)即可,选中library(“ggplot2”)点击run运行。
-
16. R语言ggplot2—使用ggdist包表征数据分布范围、置信区间、贝叶斯分布统计方法示例大全(中文教程).pdf
2021-11-15 14:24:08涵盖了目前表征数据分布范围、置信区间、贝叶斯数据统计等所有方法的统计绘图 -
9. R语言ggplot2绘图基础篇-柱状图加误差棒.pdf
2021-11-10 11:15:479. R语言ggplot2绘图基础篇-柱状图加误差棒.pdf -
r语言ggplot2说明文档及使用实例
2019-04-02 14:34:57ggplot2文档说明r语言中ggplot2包的基本函数说明及实例 -
R语言ggplot2画图专用代码
2017-11-01 14:48:09R软件及Rstudio画图大全,ggplot2里面有很多关于R原件的画图代码及图形展示。希望对你有用。 -
18. R语言_ggplot2_点线图绘制方法汇总(毕业论文、SCI论文发表必读教程).pdf
2021-11-15 14:29:28不一样的点线图绘制方法,让论文变得高大上的神器 -
R语言ggplot2可视化(细节优化)
2022-02-28 10:45:40#R语言ggplot2多图合并 library(ggpubr) ggarrange(p1,p2,p3,ncol=2,nrow=2,labels=c("A","B","C")) #去除背景色,添加坐标轴框线 p+theme_bw() #去除网格线 p+theme(panel.grid=element_blank()) #改变图例位置 ...**
R语言ggplot2可视化(细节优化)
**
#R使用ggplot()移除网格和背景#R语言ggplot2多图合并
library(ggpubr) ggarrange(p1,p2,p3,ncol=2,nrow=2,labels=c("A","B","C"))
#去除背景色,添加坐标轴框线
p+theme_bw()
#去除网格线
p+theme(panel.grid=element_blank())
#改变图例位置
p+theme(legend.position = c(0.65,0.85))
#坐标轴倾斜
p+theme(axis.text.x = element_text(angle = 45, hjust = 0.5, vjust = 0.5))
以下为大神文章链接,学习
#绘制折线图文章
ggplot2折线图的绘制
#R语言配色文章
绘图配色
#ggplot2十六进制配色P<-ggplot(data=Data, mapping=aes(x=Year, y=R, group=M)) + geom_line(aes(linetype=M,color=M) +geom_point(aes(color=M))
#改变配色
P1<-P+scale_color_manual(values=c('#666666','#000000')) #"#000000"为十六进制颜色
大神相关文章
十六进制配色(ggplot2配色)#ggplot2密度图文章
密度图(不透明,半透明)
###分割线---------------------------------------------------------------
[诗词]
青鸟不传云外信,丁香空结雨中愁。
注: 李璟(南唐中主),南唐后主李煜之父。
#终------------------------------------------------------------------------ -
玩转数据可视化之R语言ggplot2:(一)ggplot2实现箱线图、小提琴图、直方图等图形(快速入门)
2022-04-06 22:12:41玩转R语言ggplot2数据可视化 本系列主要介绍R语言ggplot2的使用 参考资料: ggplot2: Elegant Graphics for Data Analysis 文章目录玩转R语言ggplot2数据可视化1.使用案例数据 ggplot2是R语言数据可视化中的重要库之...玩转数据可视化之R语言ggplot2
- 🌸个人主页:JoJo的数据分析历险记
- 📝个人介绍:小编大四统计在读,目前保研到统计学top3高校继续攻读统计研究生
- 💌如果文章对你有帮助,欢迎关注、点赞、收藏、订阅专栏
本系列主要介绍R语言ggplot2数据可视化的使用
参考资料:
ggplot2: Elegant Graphics for Data Analysis文章目录
💘1.ggplot2基础介绍
ggplot2是R语言数据可视化中的重要库之一。本章介绍如何使用ggplot()实现重要的基本图形。
💔1.1案例数据说明
本章中,我们使用ggplot2中的自带数据集
mpg
# 导入库 library(ggplot2) # 如果没有ggplot2库,使用install.packages('ggplot2') # 查看数据集 head(mpg)
A tibble: 6 × 11 manufacturer model displ year cyl trans drv cty hwy fl class <chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr> audi a4 1.8 1999 4 auto(l5) f 18 29 p compact audi a4 1.8 1999 4 manual(m5) f 21 29 p compact audi a4 2.0 2008 4 manual(m6) f 20 31 p compact audi a4 2.0 2008 4 auto(av) f 21 30 p compact audi a4 2.8 1999 6 auto(l5) f 16 26 p compact audi a4 2.8 1999 6 manual(m5) f 18 26 p compact 各个变量解释如下:
- cty和hwy分别表示城市和公路每加仑行驶的英里数(mpg)。
- Dispt是发动机排量,单位为升。
- drv是动力系统:前轮(f)、后轮(r)或四轮(4)。
- model是车型。共有38款车型,之所以被选中,是因为它们在1999年至2008年间每年都有一款新版。
- class是描述汽车“类型”的分类变量:双座、SUV等。
💕1.2 主要组成部分
每个ggplot2绘图都有三个部分:
- 1.数据,
- 2.一系列从数据中得到的美学映射
- 3.至少包含一层要绘图的函数,ggplot2通过层级来不断在图形中增加元素
例如:
ggplot(mpg)+ aes(x = displ, y = hwy)+ geom_point()
- 其中数据是mpg
- aes()是美学映射
- geom_point是我们要绘图的函数
💖1.3 颜色、形状、大小和一些其他的美学变量
我们可以通过一些参数不断调整我们的图形
- col表示颜色
- shape表示形状
- size表示大小
# 下面我们照样画刚刚那个散点图来演示这些参数如何应用的 ggplot(mpg)+aes(displ,hwy,col=class)+ geom_point()
本例我们将col=class,则会根据class值来给不同类的点给予不同的颜色
如果我们希望设定固定的颜色,则不需要在aes里面设置参数,如下ggplot(mpg)+aes(displ,hwy)+ geom_point(col='red')
为了让代码可以重用,这里我们定义一个p来接收ggplo对象
p <- ggplot(mpg)
p + geom_point(aes(displ, hwy), col = 'blue')
这样可以使代码更简洁,大家可以参考我的R语言数据分析专栏了解更多R语言的使用
💗1.4 主要的集合图形绘制
上述我们使用了geom_point()绘制了散点图,下面介绍一些基础的图形绘制方法。
- geom_smooth():拟合一条平滑曲线,并显示其执行区间
- geom_boxplot():绘制箱线图来描述数据的分布情况
- geom_histogram()和geom_freqpoly():绘制直方图来描述数据的分布情况
- geom_bar():绘制分类型变量的分布情况
- geom_path() 和 geom_line():path()可以画出图形的轨迹,可以从右到左也可以从左到右,line()函数一班是绘制图形从左到右
✏️1.4.1 在图形上增加一个平滑曲线
当散点图有很多噪音时,这个时候我们往往较难发现变量间的关系。此时增加一条平滑线有利于我们判断变量的关系
# aes()默认第一个参数是x,第二个参数是y ggplot(mpg,aes(displ,hwy)) + geom_point()+geom_smooth()
`geom_smooth()` using method = 'loess' and formula 'y ~ x'
上图得到了散点的平衡拟合曲线,并给出了其置信区间(灰色阴影部分),我们可以设置se=FALSE不显示置信区间
geom_smooth
还有两个主要的参数是method
和span
- method指的是平滑处理的方法,默认是loess
- loess适合小样本
- gams适合大样本,需要mgcv()包
- lm适合线性拟合
- glm和lm类似,但是更稳健,需要mass()包
- span指的平衡水平,位于0-1,越大曲线越平衡
ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(span = 0.2) ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(span = 1)
`geom_smooth()` using method = 'loess' and formula 'y ~ x' `geom_smooth()` using method = 'loess' and formula 'y ~ x'
✒️1.4.2 箱线图和抖动点
当数据集包含分类型变量和数值型变量时,我们往往需要研究对于分类型变量不同取值数值型变量是怎么变化的
首先我们照样使用散点图看看是什么情况
ggplot(mpg, aes(drv, hwy)) + geom_point()
因为drv只有三个取值,并且有许多hwy相等,因此有许多重叠点,这样我们很难了解数据的分布,可以使用以下方法来解决这种问题:
- 抖动,使用geom_jitter(),对每个数据增加一点随机扰动,这样可以避免数据太多重叠点
- 箱线图,geom_boxplot(),通过一些描述性统计量来描述数据分布
- 小提琴图,geom_violin(),展示概率密度分布函数。
# 使用fill或者col指定颜色 ggplot(mpg, aes(drv, hwy)) + geom_jitter() ggplot(mpg, aes(drv, hwy,fill=drv)) + geom_boxplot() ggplot(mpg, aes(drv, hwy,fill=drv)) + geom_violin()
🖋️1.4.3 直方图和频率多边形
直方图和频率多边形一样,可以描述某一个数值型变量单独的分布情况,相较于上述方法给出了变量的更具体分布情况
# 直方图 ggplot(mpg, aes(hwy)) + geom_histogram() # 频率多边形 ggplot(mpg, aes(hwy)) + geom_freqpoly()
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`. `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
可以通过
binwidth
参数控制bin的宽度。也可以使用break控制ggplot(mpg, aes(displ, colour = drv)) + geom_freqpoly(binwidth = 0.5)
🖊️1.4.4 条形图
条形图也是来描述离散型变量的,使用geom_bar()
ggplot(mpg, aes(manufacturer)) + geom_bar()
🖌️1.4.5 时间序列图和路径图
折现图和路径图常常用于描述时序数据。折线图往往从左到右有时间顺序,而路径图往往没有时间顺序,我们使用
economics
数据集head(economics)
A spec_tbl_df: 6 × 6 date pce pop psavert uempmed unemploy <date> <dbl> <dbl> <dbl> <dbl> <dbl> 1967-07-01 506.7 198712 12.6 4.5 2944 1967-08-01 509.8 198911 12.6 4.7 2945 1967-09-01 515.6 199113 11.9 4.6 2958 1967-10-01 512.2 199311 12.9 4.9 3143 1967-11-01 517.4 199498 12.8 4.7 3066 1967-12-01 525.1 199657 11.8 4.8 3018 uempmed表示失业周期的中位数,unemploy表示每个月的失业人数,unemploy/pop表示失业率
ggplot(economics, aes(date, unemploy / pop)) + geom_line() ggplot(economics, aes(date, uempmed)) + geom_line()
从上述两个图来看两个数值随时间变化有一定差异,我们要是想研究这两个变量之间有什么关系,可以画这两个变量之间的图
ggplot(economics, aes(unemploy / pop, uempmed)) + geom_path() + geom_point()
year <- function(x) as.POSIXlt(x)$year+1900# 日期函数,得到年份 ggplot(economics, aes(unemploy / pop, uempmed)) + geom_path(colour = "grey50") + geom_point(aes(colour = year(date)))
我们可以看到,失业率和失业时间高度相关,但近年来,失业时间相对于失业率一直在增加。
💙1.5 设置坐标轴
下面我们介绍最常用的修改坐标轴的参数。
- xlab()和ylab(),给坐标轴加标签
- xlim()和ylim()设置坐标轴范围
ggplot(mpg, aes(cty, hwy)) + geom_point(alpha = 1 / 3) # 设置点的透明度 ggplot(mpg, aes(cty, hwy)) + geom_point(alpha = 1 / 3) + xlab("city driving (mpg)") + ylab("highway driving (mpg)") ggplot(mpg, aes(cty, hwy)) + geom_point(alpha = 1 / 3) + xlab(NULL) + ylab(NULL)
ggplot(mpg, aes(drv, hwy)) + geom_jitter(width = 0.25) ggplot(mpg, aes(drv, hwy)) + geom_jitter(width = 0.25) + xlim("f", "r") + ylim(20, 30) ggplot(mpg, aes(drv, hwy)) + geom_jitter(width = 0.25, na.rm = TRUE) + ylim(NA, 30)
Warning message: "Removed 141 rows containing missing values (geom_point)."
💚1.6 保存图片
在ggplot中,我们可以使用一个对象接受图片
p <- ggplot(mpg, aes(displ, hwy, colour = factor(cyl))) + geom_point()
# 使用print打印图片 print(p)
# 使用ggsave()保存图片 ggsave("plot.png", p, width = 5, height = 5)
💟文章推荐
如果想了解更多ggplot2数据可视化技巧,欢迎访问下列文章
🌟玩转数据可视化之R语言ggplot2:(二)ggplot2实现分面绘图(Faceting),包括连续变量的转换(快速入门)
🌝玩转数据可视化之R语言ggplot2:(三)ggplot2实现将多张图放在一起,包括并排和插图绘制(快速入门)
🌞玩转数据可视化之R语言ggplot2:(四)单一基础几何图形绘制 -
玩转数据可视化之R语言ggplot2:(三)ggplot2实现将多张图放在一起,包括并排和插图绘制(快速入门)
2022-04-08 21:51:51玩转R语言ggplot2数据可视化 小编大四统计在读,目前保研到统计学top3高校继续攻读统计研究生。本系列主要介绍R语言ggplot2的使用 参考资料: ggplot2: Elegant Graphics for Data Analysis 文章目录玩转R语言ggplot... -
R语言ggplot2分组条形图
2020-10-31 10:01:37这里写目录标题1. 基本分组条形图2. 使柱子并排放置3. 改变条形图配色4. 使纵坐标呈现百分比5.... 语言 = rep(c('R','Python'),2), 比例 = c(0.8,0.2,0.1,0.9)) 现在想以专业为横坐标,比例为纵坐标,语言为组 -
R语言ggplot2修改图例
2020-01-04 15:05:02R语言修改图例。 -
R语言 ggplot2 多图排列 Part(1)
2021-05-25 20:45:54仔细想想,好不容易用ggplot2画出了至少看上去高上大的图,到头来还是要靠PPT排版,是不是心里会有些不甘心呢。如果和我一样选择是的小伙伴,那请继续往下看文章,肯定可以给你带来不一样的体验。 本文使用到的包有... -
R语言ggplot2画图
2022-02-09 22:52:16R语言散点图,条形图,箱型图,折线图,直方图 -
13. R——ggplot2 多个图例分离显示方法汇总.pdf
2021-11-10 11:13:3113. R——ggplot2 多个图例分离显示方法汇总.pdf -
R语言ggplot2包绘制散点图详解
2020-03-19 09:44:44R语言的ggplot包可以实现各种复杂的制图功能,本文以散点图为例,介绍ggplot2代码的使用方法。 首先,使用R内置数据attitude绘制complaints和learning的散点图。请注意ggplot2语法和R原生代码的区别。ggplot2采用... -
玩转数据可视化之R语言ggplot2:(八)ggplot2绘制空间地理数据图
2022-04-14 17:14:01玩转数据可视化之R语言ggplot2 个人主页:JoJo的数据分析历险记 个人介绍:小编大四统计在读,目前保研到统计学top3高校继续攻读统计研究生 如果文章对你有帮助,欢迎关注、点赞、收藏、订阅专栏 本系列主要介绍R... -
玩转数据可视化之R语言ggplot2:(二)ggplot2实现分面绘图(Faceting),包括连续变量的转换(快速入门)
2022-04-07 18:13:59玩转R语言ggplot2数据可视化 本系列主要介绍R语言ggplot2的使用 参考资料: ggplot2: Elegant Graphics for Data Analysis 文章目录玩转R语言ggplot2数据可视化2.玩转数据可视化之R语言ggplot2:(二)实现分面画图... -
R语言ggplot2-堆叠图
2021-04-28 09:29:24ggplot(data = cell,aes(x=ma,,y=count,fill=groupe))+ geom_bar(stat="identity",position = "fill")+ ##添加辅助线 geom_hline(yintercept=0.25,linetype=2,size=1)+ ##旋转坐标轴 coord_flip()+xlab("")+ theme_... -
R语言ggplot2图例标签、标题、顺序修改和删除
2021-03-09 10:11:03图例 修改图例标注 scale_colour_discrete(#values=c("#CC0000", "#006600", "#669999", # "#00CCCC", "#660099"),或者color/fill/colour,... breaks = c("1","2","3","4","5"), labels = c("A","B","C","D","E")) -
R语言ggplot2频率分布直方图小例子
2021-01-12 21:23:08第一步:准备数据将准备用直方图展示的数据整理在excel中,每个变量一列,比如本文用到的例子第二步:ggplot2作图读入数据exampledfpathdfheader=TRUE参数是因为刚刚保存的数据中有表头,如果自己的数据没有表头,... -
R语言ggplot2 - theme()主题设置
2021-12-29 19:15:59前言 (个人学习笔记,供学习参考,如有不足之处,还请大佬们批评指正!...【R语言-ggplot2学习-概览】 接下来跟着官方帮助文档学一些基本的。 先来画一个原始的散点图: p1 <- ggplot(mtcars, aes(wt,