R语言

ggplot2图形对象(绘图元素和基本要求)

2018-11-13  本文已影响106人  抠脚_b41d

最近做了很多乱七八糟的图,发现ggplot2确实是个好东西,这里最一些简单的记录,以便今后绘图查阅

1.图形对象

ggplot一般会产生一个ggplot对象,获得方法是和对象类型同名的函数ggplot。它的基本用法格式如下

ggplot(df,aes(x,y,<other aesthetics>
ggplot(df)
ggplot()

df是数据框,aes用于参数的设定。
以下代码产生一个图形对象,qplot是快速产生ggplot对象的一个函数

library(ggplot2)
theme_set(theme_bw())
x=1:100
y=rnorm(100)
p1=plot(x,y)
p2=qplot(x,y)
散点图

我们执行p1p2的赋值不会生成图片。我们用class函数看看p1p2是什么

class(p1)   ###[1] "NULL"
class(p2)   ###[1] "gg"     "ggplot"

print(p2) ##打印图形

2.ggplot图形对象组成(我们记录下一些需要注意的地方)

names(p2) # [1] "data"  "layers" "scales"  "mapping"  "theme"   "coordinates"  "facet"  "plot_env"   "labels"

2.1映射

绘图的时候,在指定数据的时候,会形成映射,什么是映射?比如我们现在使用diomands这个R内置数据集来画个图

p3 <- qplot(carat, price, data=diamonds, color=cut, shape=cut)

什么意思呢?
数据是diamonds这个数据框的,x是carat,y是price,color和shape分别由cut这一项决定。
映射是ggplot对象中的一个属性,这种映射方式决定我们代码的方式。

2.2图层layers

图层至少包含三个东西:geom,stat和position
集合类型geom:数据在图上的展示形式,即点、线、面等。ggplot2有很多预设的几何类型
统计类型stat:对数据所应用的统计方法
位置position:几何图像的位置调整,也有默认设定
指定了集合类型或者统计类型,图层就会战胜 比如:geom_point()
我们使用图层加法在一个ggplot对象疯狂加新的元素,而不替换图层,这就是ggplot2操作秀的地方
比如

p4 <- ggplot(diamonds)+aes(x=carat, y=price, color=cut, shape=cut)+geom_point(color="red") + geom_point(color="blue")
p4 <- ggplot(diamonds)+aes(x=carat, y=price, color=cut, shape=cut)+geom_point(color="blue") + geom_point(color="blue")
diamonds数据集添加图层绘图

2.3主题theme

标题文字(字体、字号、颜色)、图形边框和底纹等和数据无关的都由主题这一因素控制。ggplot2提供了四个成套的主题给用户:分别是theme_gray(), theme_bw() , theme_minimal() 和 theme_classic()。我们可以根据个人偏好需要选择。

p5 <- p4 + geom_point(color="blue")
p5 + theme_gray() + ggtitle("theme_gray()")
p5 + theme_bw() + ggtitle("theme_bw()")
p5 + theme_minimal() + ggtitle("theme_minimal()")
p5 + theme_classic() + ggtitle("theme_classic()")
gray主题背景

我们作图需要了解的大概就是这些。这时我们可以轻松完成一些比较简单的作图了。

上一篇 下一篇

猜你喜欢

热点阅读