学习了ggplot2 的一些最基本的东西,有了一些细微的发现。对于画图来说,要引起注意。 1.散点图。点的颜色和形状的控制,放置的位置有讲究。如放置aes()里面,还是geom_point()里面大不相同。 library("ggplot2") str(mtcars) 'data.frame': 32 obs. of 13 variables: $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ... ggplot(mtcars,aes(x=wt,y=mpg,col=am1,shape=am1))+geom_point(size=2)
而:ggplot(mtcars,aes(x=wt,y=mpg))+geom_point(col=mtcars$am1,shape=mtcars$am1)结果会是什么呢? 结果:Error in grDevices::col2rgb(colour, TRUE) : '手动'颜色名字不对。 如果是:ggplot(mtcars,aes(x=wt,y=mpg))+geom_point(col=mtcars$cyl,shape=mtcars$cyl)结果会是什么呢? 还是错误么?
可以发现,图像出来了,但是里面并没有图例。想想为什么(mtcars$am1没有图像,而mtcars$cyl 确出来了) 如果换成:ggplot(mtcars,aes(x=wt,y=mpg,col=mtcars$cyl,shape=mtcars$cyl))+geom_point()
此图与上图相比,图例出来了,形状和上图并不相同。因此如果是按照不同的面板或类别来区分的话,点和形状的控制就要放到aes()里面。 而且数值型的必须转换成factor类型#factor(data,levels=c(0,1,2,3),labels=c("a","b","c","d")),用以区分类别。 如果是分面板: > ggplot(mtcars,aes(x=wt,y=mpg,col=mtcars$gear1,shape=mtcars$gear1))+geom_point()+facet_grid(mtcars$am1~.)
注意~. 表示的意义,漏掉"."会报错。 2.直方图 ggplot(mtcars,aes(x=gear,fill=am1))+geom_bar()
默认是叠加的,如果改为类别非叠加的则,ggplot(mtcars,aes(x=gear,fill=am1))+geom_bar(position = "dodge"),见下图。
ggplot(mtcars,aes(x=gear,fill=am1))+geom_bar(position = "fill")
由此可见:position 对于条形图来说,具有“生杀大权”。 #dodge 是躲避回避的意思。 |
|
来自: 杉杉之园 > 《ggplot2绘图》