ggplot2的简单实用

ggplot2的简单实用

本文参考了《ggplot2作图详解》http://www.plob.org/2014/01/24/7452.html, 这篇文章比较详细介绍ggplot2的绘图过程,本文只是一个简单使用的总结,能满足数据分析过程的大部分图标要求。

ggplot2包有两个绘图方法,一个是qplot,一个是ggplot方法。

qplot()函数即 quick plot(快速绘图),是R语言的plot过渡到ggplot而存在的,怕用户直接使用ggplot不习惯,当然qplot也包含了ggplot的很多思想,在使用qplot会慢慢理解ggplot的映射,分组,图层等的概念。虽然使用qplot函数也能实现大部分ggplot的功能,但是只是用qplot就没办法体现ggplot的强大了。

ggplot()函数是ggplot2包的核心函数,也是我们要重点学习的。但是也不难,因为我们只是使用它的绘图接口,常用的图形也就是那几个,从学以致用的角度来说是很容易的。

1.qplot函数的使用

qplot(x, y = NULL, ..., data, facets = NULL,
      margins = FALSE, geom = "auto", stat = list(NULL),
      position = list(NULL), xlim = c(NA, NA),
      ylim = c(NA, NA), log = "", main = NULL,
      xlab = deparse(substitute(x)),
      ylab = deparse(substitute(y)), asp = NA)
  • x, y: 告诉qplot应该使用什么数据作为x轴和y轴。
  • data: 这个可以有,为数据框(data.frame)类型;如果有这个参数,那么x,y的名称必需对应数据框中某列变量的名称。
  • facets: 图形/数据的分面。这是ggplot2作图比较特殊的一个概念,它把数据按某种规则进行分类,每一类数据做一个图形,所以最终效果就是一页多图。
  • margins: 是否显示边界
  • geom: 图形的几何类型(geometry),这又是ggplot2的作图概念。ggplot2用几何类型表示图形类别,比如point表示散点图、line表示曲线图、bar表示柱形图等。
  • stat: 统计类型(statistics),这个更加特殊。直接将数据统计和图形结合,这是ggplot2强大和受欢迎的原因之一。
  • position: 图形或者数据的位置调整,这不算太特殊,但对于图形但外观很重要
  • xlim, ylim, xlab, ylab, main: 可以按照plot函数的相应参数来理解,x,y轴的范围,标签,主标题
  • 其他参数:color:指定颜色,size:指定大小,shape:指定形状。如果是因子型变量,则会分组绘图。

1.1 散点图(默认)

str(diamonds)
set.seed(1000) # 设置随机种子
datax<- diamonds[sample(53940, 100), seq(1,7)] #抽100条数据绘图
qplot(x=carat, y=price, data=datax, xlab="Carat", ylab="Price", main="这是散点图")

1.2 分组绘图

这个概念可以理解为不同因子水平的数据用不同颜色,大小,形状来标记。
color:颜色
shape:形状
size:大小

qplot(x=carat, y=price, data=datax, color=cut, shape=cut, main="分组绘图")

1.3 其他图形

使用qplot绘制其他图形通过 geom 参数指定。
- point:散点图
- line:曲线图
- smooth:平滑曲线,拟合曲线
- jitter:另一种散点图
- boxplot:箱线图
- histogram:直方图
- density:密度分布图
- bar:柱状图

# 曲线图
qplot(x=carat, y=price, data=datax, color=cut, geom="line", main="曲线图")

# 曲线图+散点图
qplot(x=carat, y=price, data=datax, color=cut, geom=c("line", "point"), main="曲线图+散点图")

# 拟合曲线(平滑曲线)
qplot(carat, price, data = diamonds, color=cut, geom = "smooth", main = "拟合曲线")

# 箱线图
qplot(cut, price, data = diamonds, fill=cut, geom = "boxplot", main = "箱线图")

# 直方图
qplot(price, data = diamonds, fill=cut, geom = "histogram", main = "直方图")

# 密度分布图
qplot(price, data = diamonds, color=cut, geom = "density", main = "密度分布图")

1.4 柱状图

做柱形图很少直接用原始数据,一般都要通过计算变换如求平均值,计数后再做。这其实是一个统计过程,所以多数柱形图应该也是统计类型的图。ggplot2对柱形图的处理体现了这一思想:柱形图是一种特殊的直方图。所以ggplot2可以直接用原始数据做出柱形图,这是它的优点之一。
通过 stat 和 fun.y 和指定统计函数

# 柱状图
qplot(x=cut, y=price, data = diamonds, fill=cut, geom = "histogram",stat="summary", fun.y="mean")

2 ggplot的简单使用

ggplot绘图使用类似PS图层的概念,底层是一个空的图层,但是指定了x,y轴的数据映射,颜色,形状,大小等映射也可以指定。然后在底层图层上面不断添加的点图,曲线图等的其他图层,在添加图层的时候也可以指定和底层图层不同的颜色,形状等的映射。

下面是一个简单的但是比较全的ggplot的使用过程。

# 1.选择500条记录画图
library(ggplot2)
set.seed(100)
d.sub <- diamonds[sample(nrow(diamonds), 500), ]

# 2.作图首先要指定x和y数据,即建立数据框变量和x/y之间的映射:
p  <- ggplot(data=d.sub, aes(x=carat, y=price))

# 3.作出散点图
p  + geom_point()

# 4.如果还要建立其他映射,比如用钻石颜色(color),形状(cut)分类数据确定点的颜色,图形外观就会发生变化

p  + geom_point() + aes(color=color, shape=cut)
#或者
p  + geom_point(aes(color=color, shape=cut))

2.1 ggplot支持的geom_绘图类型

ls("package:ggplot2", pattern="^geom_.+")
函数说明
geom_ablineLines: horizontal, vertical, and specified by slope and intercept.
geom_barBars, rectangles with bases on x-axis
geom_bin2dAdd heatmap of 2d bin counts.
geom_blankBlank, draws nothing.
geom_boxplotBox and whiskers plot.
geom_contourDisplay contours of a 3d surface in 2d.
geom_countCount the number of observations at each location.
geom_densityDisplay a smooth density estimate.
geom_density2dContours from a 2d density estimate.
geom_dotplotDot plot
geom_errorbarhHorizontal error bars
geom_hexHexagon binning.
geom_freqpolyHistograms and frequency polygons.
geom_jitterPoints, jittered to reduce overplotting.
geom_crossbarVertical intervals: lines, crossbars & errorbars.
geom_mapPolygons from a reference map.
geom_lineConnect observations.
geom_pointPoints, as for a scatterplot
geom_polygonPolygon, a filled path.
geom_quantileAdd quantile lines from a quantile regression.
geom_areaRibbons and area plots.
geom_rugMarginal rug plots.
geom_curveLine segments and curves.
geom_smoothAdd a smoothed conditional mean.
geom_spokeA line segment parameterised by location, direction and distance.
geom_labelTextual annotations.
geom_rasterDraw rectangles.
geom_violinViolin plot.
geom_qqCalculation for quantile-quantile plot.
update_geom_defaultsModify geom/stat aesthetic defaults for future plots

2.2 ggplot支持的 stat_ 统计函函数

ls("package:ggplot2", pattern="^stat_.+")
[1] "stat_bin"         "stat_bin_2d"      "stat_bin_hex"     "stat_bin2d" 
[5] "stat_binhex"      "stat_boxplot"     "stat_contour"     "stat_count" 
[9] "stat_density"     "stat_density_2d"  "stat_density2d"   "stat_ecdf"  
[13] "stat_ellipse"     "stat_function"    "stat_identity"    "stat_qq"   
[17] "stat_quantile"    "stat_smooth"      "stat_spoke"       "stat_sum"  
[21] "stat_summary"     "stat_summary_2d"  "stat_summary_bin" "stat_summary_hex"
[25] "stat_summary2d"   "stat_unique"      "stat_ydensity" 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值