|||
My notes for R programming
Based on electronic version of R for data science
20200206-20200207 chapter1- chapter3- Data visualization
#This blog mainly focuses on chapter 3 -Data visualization
library(ggplot2) #使用前先载入包
#h绘图模板如下:
ggplot(data = <DATA>) +
<GEOM_FUNCTION>(mapping = aes(<MAPPINGS>))
#ggplot2有很多geom函数,如geom_smooth,geom_point,geom_boxplot等,每个geom函数都有一个mapping参数,定义变量的mapping方式
#mapping 和aes()通常一起出现, aes里是绘图参数,不同的geom函数包含的aes参数不完全一样,共有x=varible_name,y=,cologgr等;但smooth里有linetype = variable_name,group = variable_name, 而point里没有。
#> Warning: Using size for a discrete variable is not advised.
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, color = trans)) #或者自定义颜色geom_point(mapping = aes(...), color = "blue")
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(. ~ class) #两个变量时可以用facet_wrap也可以用facet_grid,区别是前者变量同轴排列,后者异轴排列(网格数量为x*y个,不能设置nrow和ncol)。
#用 . 代替x/y轴的变量,则所在轴只有一行/列
coord_flip() #转换横纵坐标系
ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) + #全局设置,还可以设置color等共有的aes参数
geom_point() + #该图层接受全局设置,无单独设置;
geom_abline(size = 2, color = "orange") + #该图层单独设置;括号里不能写mapping = aes(size = ...),而是这样写!!!!
coord_fixed()
> ggplot(data = mpg, mapping = aes(displ,hwy))+
geom_point(color = drv)+ #没加mapping=aes不能设置(???),下同
geom_smooth(se = FALSE , size = 2, group = drv)
#Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomPoint, : 找不到对象'drv'
> ggplot(data = mpg, mapping = aes(displ,hwy))+
geom_point(mapping = aes(color = drv))+
geom_smooth(mapping = aes(size = 2, group = drv),se = FALSE)
#geom_smooth()` using method = 'loess' and formula 'y ~ x'
#template
ggplot(data = <DATA>) +
<GEOM_FUNCTION>(
mapping = aes(<MAPPINGS>),
stat = <STAT>,
position = <POSITION>
) +
<COORDINATE_FUNCTION> +
<FACET_FUNCTION>
#The grammar of graphics is based on the insight that you can uniquely describe any plot as a combination of a dataset, a geom, a set of mappings, a stat, a position adjustment, a coordinate system, and a faceting scheme.
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-11-13 23:50
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社