第 8 课

ggplot2绘图

课程讲义导读 · 聚焦本课核心概念、分析流程与复现要点

说明:本页适合用于快速回顾本课重点、关键步骤与常用示例。

主讲老师第八课:ggplot2绘图

大家可以先把这部分代码解压打开(ggplot2 包.zip),讲完了基础包绘图后,我们来看一下如何使用强大的 ggplot2 进行数据的可视化,确实,在 R 语言中存在好几种绘图工具,但是 ggplot2 无疑是其中最优雅、功能全面的一个。ggplot2 是由 Hadley Wickham 创建的一个十分强大的可视化 R 包。在 ggplot2 中,可以使用 ggplot() 函数开始绘图对于 ggplot2的绘图逻辑,其实是通过图层叠加的概念最终完成图像的绘制,其中一句语句代表一张图,然后再有最小的单元图层进行绘制。因此,按照 ggplot2 的绘图理念,Plot(图)= data(数据集)+Aesthetics(美学映射)+ Geometry(几何对象)这部分如何理解?

按照P图理解即可,磨皮一下+瘦个脸+大个眼睛,组合起来就是一张美丽的图片啦接下来,我们将根据 ggplot2 的基本要素逐步介绍这个强大的 R 可视化包:

1). 数据(Data):数据框对象;

2). 映射(Mapping):由 aes()函数来设置映射;3).几何对象(Geometric);4).统计变换(Statistics);5).标度(Scale);6).坐标系统(Coordinante);7).分面(Facet);8).主题(Theme)

1.R 包的安装与数据准备

1.1 R 包安装

对于 ggplot2 的安装,直接从 CRAN 上通过 install.packages()命令,即可快速完成安装,同时,ggplot2 包是 tidyverse 包中的核心 R 包之一,因此,如果直接安装 tidyverse 也能完成安装过程核心包不明白什么意思?快去看复习前面的内容

1.2 数据集

这里,我们主要使用 ggplot2 包中的 mpg 数据作为示例数据进行演示其中包含了由美国环境保护协会收集的 38 种车型的各种数据。数据(Data)是用于绘制图形的数据,即指定要用到的数据源。在绘图过程中,我们需要指定要用到的数据源,必须使用数据框类型.

2.创建 ggplot 图形

接下来,我们使用 ggplot2 包先来绘制一幅简单的图形。

整个绘图过程,我们可以对其进行拆分,首先我们通过 ggplot(data = mpg) 来创建一张新的图层,使用参数 data = mpg 来指定图中使用的数据集。接着,我们向 ggplot()中继续添加其他图层信息,使用geom_point() 函数向上一个图层中添加一个散点图,其中将 displ信息添加至 x 轴,hwy 添加到 y轴。这样,一张简单的散点图就绘制完成了接下来,在这张图的基础上,对其进行修改。映射(Mapping):指将数据集中的数据关联到相应的图形属性过程中一种对应关系。在ggplot2 中,mapping 参数总是与 aes()函数总是成对出现,通过 aes()函数来指定映射,把图形属性和数据关联起来,因此,基于ggplot2 包的最基础绘图模版总结如下。

大家直接往< >里面填入相应的内容即可完成图形的绘制在图形映射中,除了常用参数 x 和 y 外,还有一些常用的图形属性与参数,如颜色(color),大小(size),形状(shape),透明度(alpha),以及填充颜色(fill)等。来简单对这些映射进行修改1). 修改颜色(color)映射结果显示,通过 class 的不同分组类型,对颜色进行了分配2). 修改大小(size)映射结果显示,此时根据 class 类型对点的大小进行了修改。

3). 修改透明度(alpha)映射

3.几何对象(Geometric)

关于几何对象,其是指图中用来表示数据的图形对象。也许对于这个概念而言,大家仍然不太理解这到底是指什么内容。简单来讲,如之前的几幅图里所展示的内容,其使用的都是 geom_point()函数得到的点几何对象。此外,如条形图使用的是条形几何对象,折线图使用直线几何对象,箱线图使用矩形和直线几何对象。如果想要修改图中的几何对象,只要在ggplot()函数上调整相应的几何对象函数即可。接下来,看几个相关的例子使用 geom_point()绘制点几何对象。

接着,修改为 geom_smooth()线几何对象。

如上面两张图所示,第一张图使用的是点几何对象,第二张图使用的是平滑曲线几何对象。但是,有几

个注意事项需要注意:

1). 尽管每个几何对象函数都有一个 mapping 参数,但并不是每种图形属性都适合每种几何对象。比如:点几何对象中我们可以设置其形状,但是线条不存在形状的说法,在线条中其对应的是“线型”。

我们可以根据变量 drv 的分组来赋予不同的线型。

2). 基于 ggplot 绘图时图层叠加的原理,不同的几何对象之间是可以叠加的同时使用两个几何对象,可以看到,点图和线图同时展示在了图中,并且两者均基于变量 drv 的内容进行了分组。

3). 全局映射 & 局部映射在不同几何对象叠加的同时,不知道大家有没有发现,参数 mapping 中有些语句重复多次出现,这样代码就发生了重复,对此现象,我们可以将这些映射内容传递给 ggplot()函数。这样一来,ggplot2 会将这部分映射作为全局映射应用到每个几何对象中。举个例子,对上面那句代码进行修改:

将共同部分作为全局映射,其余作为局部映射。

可以看到,两者得到的结果是一样的。

4.统计变换(Statistics)

在绘图时候,有些图形需要先通过计算生成一个新变量结果,这种用来计算新数据的算法叫做统计变换,缩写为 stat。

使用 geom_bar()函数得到的图形纵坐标是 count 值,纵坐标 count 值是一个经过计算得到的新数据,因为 geom_bar() 函数的默认统计转换方式是 stat_count() 形式,经过 stat_count() 计算后会得到两个新变量,分别是 count 值(计数)和 prop(proportion,比例)。

直接使用 stat_count()函数绘制得到的图形与 geom_bar()的结果是一样的,而且两者之间并不存在优劣之分。

4.1 直接使用计数值进行绘图

有时候,我们并不想系统进行统计转换,而是直接展示所提供的数据进行作图。这时候,就需要借助另外一个参数,即 stat = ‘identity’,进而进行显著统计变换过程。

绘图前,我们先准备一个新的数据,使用 table()函数对 cut 中的不同分组进行统计,并 生成一个新的数据框可以看到,在新生成的数据框中,第一列是 cut 的不同类型,第二列为每个类型对应的数量,并且,将第一列的列名定义为“Type”。这里注意一下,自己定义的列名最好中间不要存在空格。

通过参数 stat = "identity"的定义,结果显示,在图中,直接将每个 Type 中变量对应的数值展示在了图中

4.2 使用 prop(比例)进行绘图

此外,当我们不想展示 count,而是想向展示各组所占的比例时,可以借助 y = ..prop.. 来展示结果。

在图中,可以看到,y 轴展示的是各组所占比例,且总和为 1。

5.位置调整

正式讲解这个板块前,首先我们先来看一下 color 和 fill 两个参数的使用区别。

对比一下接下来的第二张图:

对比两个图,可以看出,在条形图中,color 主要赋值给条形图的边框,而 fill 则主要是填充整个条形图。接着,当给 fill 按变量 clarity 进行赋值时,那么条形图会自动分配颜色对于条形图中每个板块的堆叠,我们也可以通过对参数 position 进行调整。下面,我们来简单介绍一下参数 position 的三种常见设置。

5.1 参数 position = "identity"

5.2 参数 position = "fill"

5.3 参数 position = "dodge"

下面,我们来讲解一下三种参数的差异之处:

1). position = "identity"其主要起到堆叠效果,将每个对象直接展示在图中2). position = "fill"效果与堆叠相似,但是每组堆叠后的条形图都具有相同的高度3). position = "dodge"将每组中的条形一次并列放置,可以比较明显地展示和比较每个条形图的具体数值,其中,position = "dodge"的使用是不是和昨天基础包部分 barplot()函 数的参数beside = TRUE 很像呢?

6.坐标系

此外,还有一些常用的知识点,在 ggplot2 中默认使用的是笛卡尔直角坐标系

6.1 coord_flip()函数

coord_flip()`函数可以交换 x 轴和 y 轴,这对于有些图形的展示可以起到一些非常有意义的效果,尤其是 x 轴很长的时候。

当不加参数 coord_flip()时,x 轴为 class 分组情况,通过 geom_boxplot()函数来展示箱线图几何对象。

接着,我们进行坐标轴的转置。

当加上 coord_flip() 参数时,可以看到 x 轴和 y 轴的内容进行了颠倒,这对于平时看惯了正常图形的大家来说,使用这种图形说不定也可以起到不错的效果

6.2 coord_polar()函数

使用 coord_polar() 函数后,生成极坐标,可以更好的展示图形结果常用的参数就介绍到这里了,有些其他可能需要用到的参数在后续的内容中会做进一步介绍,同时,对ggplot()函数绘图的语法进行简单的总结。

从数据,到映射,几何对象,位置,以及坐标系的转换,总结在这张图里Data Visualization with ggplot2 : : CHEAT SHEETBasics Geoms Use a geom function to represent data points, use the geom’s aesthetic properties to represent variables.Each function returns a layer.GRAPHICAL PRIMITIVES TWO VARIABLESggplot2 is based on the grammar of graphics, the ideathat you can build every graph from the same a <- ggplot(economics, aes(date, unemploy)) continuous x , continuous y continuous bivariate distributioncomponents: a data set, a coordinate system, b <- ggplot(seals, aes(x = long, y = lat)) h <- ggplot(diamonds, aes(carat, price))e <- ggplot(mpg, aes(cty, hwy))and geoms—visual marks that represent data points. a + geom_blank() e + geom_label(aes(label = cty), nudge_x = 1, h + geom_bin2d(binwidth = c(0.25, 500))(Useful for expanding limits) nudge_y = 1, check_overlap = TRUE) x, y, label, x, y, alpha, color, fill, linetype, size, weightF M A alpha, angle, color, family, fontface, hjust,b + geom_curve(aes(yend = lat + 1, lineheight, size, vjust+ = xend=long+1,curvature=z)) - x, xend, y, yend,alpha, angle, color, curvature, linetype, size e + geom_jitter(height = 2, width = 2)h + geom_density2d()x, y, alpha, colour, group, linetype, sizex, y, alpha, color, fill, shape, sizedata geom coordinate plot a + geom_path(lineend="butt", linejoin="round", h + geom_hex()x=F·y=A system linemitre=1) x, y, alpha, colour, fill, sizee + geom_point(), x, y, alpha, color, fill, shape,x, y, alpha, color, group, linetype, size size, strokeTo display values, map variables in the data to visual a + geom_polygon(aes(group = group)) e + geom_quantile(), x, y, alpha, color, group,properties of the geom (aesthetics) like size, color, and x x, y, alpha, color, fill, group, linetype, size linetype, size, weight continuous functionand y locations. i <- ggplot(economics, aes(date, unemploy))b + geom_rect(aes(xmin = long, ymin=lat, xmax=F M A long + 1, ymax = lat + 1)) - xmax, xmin, ymax, e + geom_rug(sides = "bl"), x, y, alpha, color, i + geom_area()ymin, alpha, color, fill, linetype, size x, y, alpha, color, fill, linetype, size+ =linetype, sizea + geom_ribbon(aes(ymin=unemploy - 900, e + geom_smooth(method = lm), x, y, alpha, i + geom_line()ymax=unemploy + 900)) - x, ymax, ymin, color, fill, group, linetype, size, weight x, y, alpha, color, group, linetype, sizedata geom coordinate plot alpha, color, fill, group, linetype, sizex=F·y=A systemcolor = F e + geom_text(aes(label = cty), nudge_x = 1, i + geom_step(direction = "hv")size = A nudge_y = 1, check_overlap = TRUE), x, y, label, x, y, alpha, color, group, linetype, sizealpha, angle, color, family, fontface, hjust,LINE SEGMENTS lineheight, size, vjustcommon aesthetics: x, y, alpha, color, linetype, sizeb + geom_abline(aes(intercept=0, slope=1)) visualizing errorComplete the template below to build a graph. b + geom_hline(aes(yintercept = lat)) df <- data.frame(grp = c("A", "B"), fit = 4:5, se = 1:2)required b + geom_vline(aes(xintercept = long)) discrete x , continuous y j <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se))ggplot (data = <DATA> ) + f <- ggplot(mpg, aes(class, hwy))b + geom_segment(aes(yend=lat+1, xend=long+1)) j + geom_crossbar(fatten = 2)<GEOM_FUNCTION> (mapping = aes( <MAPPINGS> ), x, y, ymax, ymin, alpha, color, fill, group, linetype,b + geom_spoke(aes(angle = 1:1155, radius = 1)) f + geom_col(), x, y, alpha, color, fill, group,stat = <STAT> , position = <POSITION> ) + Not linetype, size size<COORDINATE_FUNCTION> + required,sensible j + geom_errorbar(), x, ymax, ymin, alpha, color,f + geom_boxplot(), x, y, lower, middle, upper, group, linetype, size, width (also<FACET_FUNCTION> + defaultssupplied ONE VARIABLE continuous ymax, ymin, alpha, color, fill, group, linetype, geom_errorbarh())<SCALE_FUNCTION> + shape, size, weightc <- ggplot(mpg, aes(hwy)); c2 <- ggplot(mpg)j + geom_linerange()<THEME_FUNCTION> f + geom_dotplot(binaxis = "y", stackdir = x, ymin, ymax, alpha, color, group, linetype, sizec + geom_area(stat = "bin") "center"), x, y, alpha, color, fill, groupx, y, alpha, color, fill, linetype, size j + geom_pointrange()ggplot(data = mpg, aes(x = cty, y = hwy)) Begins a plot f + geom_violin(scale = "area"), x, y, alpha, color, x, y, ymin, ymax, alpha, color, fill, group, linetype,that you finish by adding layers to. Add one geom c + geom_density(kernel = "gaussian") fill, group, linetype, size, weight shape, sizefunction per layer. x, y, alpha, color, fill, group, linetype, size, weightaesthetic mappings data geomc + geom_dotplot() mapsqplot(x = cty, y = hwy, data = mpg, geom = “point") x, y, alpha, color, fill data <- data.frame(murder = USArrests$Murder,Creates a complete plot with given data, geom, and discrete x , discrete y state = tolower(rownames(USArrests)))mappings. Supplies many useful defaults. c + geom_freqpoly() x, y, alpha, color, group, g <- ggplot(diamonds, aes(cut, color)) map <- map_data("state")linetype, size k <- ggplot(data, aes(fill = murder))last_plot() Returns the last plot g + geom_count(), x, y, alpha, color, fill, shape, k + geom_map(aes(map_id = state), map = map)c + geom_histogram(binwidth = 5) x, y, alpha,ggsave("plot.png", width = 5, height = 5) Saves last plot color, fill, linetype, size, weight size, stroke + expand_limits(x = map$long, y = map$lat),as 5’ x 5’ file named "plot.png" in working directory. map_id, alpha, color, fill, linetype, sizeMatches file type to file extension. c2 + geom_qq(aes(sample = hwy)) x, y, alpha,color, fill, linetype, size, weightTHREE VARIABLESseals$z <- with(seals, sqrt(delta_long^2 + delta_lat^2))l <- ggplot(seals, aes(long, lat))discrete l + geom_contour(aes(z = z)) l + geom_raster(aes(fill = z), hjust=0.5, vjust=0.5,d <- ggplot(mpg, aes(fl)) x, y, z, alpha, colour, group, linetype, interpolate=FALSE)size, weight x, y, alpha, filld + geom_bar()x, alpha, color, fill, linetype, size, weight l + geom_tile(aes(fill = z)), x, y, alpha, color, fill,linetype, size, widthRStudio® is a trademark of RStudio, Inc. • CC BY RStudio • [email protected] • 844-448-1212 • rstudio.com • Learn more at http://ggplot2.tidyverse.org • ggplot2 2.1.0 • Updated: 2016-11Stats An alternative way to build a layer Scales Coordinate Systems FacetingA stat builds new variables to plot (e.g., count, prop). Scales map data values to the visual values of an r <- d + geom_bar() Facets divide a plot intofl cty cyl aesthetic. To change a mapping, add a new scale. r + coord_cartesian(xlim = c(0, 5)) subplots based on thexlim, ylim values of one or more(n <- d + geom_bar(aes(fill = fl)))+ =x ..count..The default cartesian coordinate system discrete variables.aesthetic prepackaged scale-specific r + coord_fixed(ratio = 1/2)scale_ to adjust scale to use arguments ratio, xlim, ylim t <- ggplot(mpg, aes(cty, hwy)) + geom_point()data stat geom coordinate plot Cartesian coordinates with fixed aspect ratiox=x· system n + scale_fill_manual( between x and y unitsy = ..count.. values = c("skyblue", "royalblue", "blue", “navy"), r + coord_flip() t + facet_grid(. ~ fl)Visualize a stat by changing the default stat of a geom limits = c("d", "e", "p", "r"), breaks =c("d", "e", "p", “r"), xlim, ylim facet into columns based on flname = "fuel", labels = c("D", "E", "P", "R")) Flipped Cartesian coordinatesfunction, geom_bar(stat="count") or by using a stat t + facet_grid(year ~ .)r + coord_polar(theta = "x", direction=1 ) facet into rows based on yearfunction, stat_count(geom="bar"), which calls a default range of title to use in labels to use breaks to use in theta, start, directionvalues to include legend/axis in legend/axis legend/axisgeom to make a layer (equivalent to a geom function). in mapping Polar coordinates t + facet_grid(year ~ fl)Use ..name.. syntax to map stat variables to aesthetics. r + coord_trans(ytrans = “sqrt") facet into both rows and columnsxtrans, ytrans, limx, limy t + facet_wrap(~ fl)GENERAL PURPOSE SCALES Transformed cartesian coordinates. Set xtrans and wrap facets into a rectangular layoutgeom to use stat function geommappings ytrans to the name of a window function.Use with most aestheticsi + stat_density2d(aes(fill = ..level..), Set scales to let axis limits vary across facetsscale_*_continuous() - map cont’ values to visual ones π + coord_quickmap()geom = "polygon") 60variable created by stat scale_*_discrete() - map discrete values to visual ones π + coord_map(projection = "ortho", t + facet_grid(drv ~ fl, scales = "free")latscale_*_identity() - use data values as visual ones orientation=c(41, -74, 0))projection, orienztation, x and y axis limits adjust to individual facetsxlim, ylim "free_x" - x axis limits adjustc + stat_bin(binwidth = 1, origin = 10) scale_*_manual(values = c()) - map discrete values to longMap projections from the mapproj packagemanually chosen visual ones "free_y" - y axis limits adjustx, y | ..count.., ..ncount.., ..density.., ..ndensity.. (mercator (default), azequalarea, lagrange, etc.)scale_*_date(date_labels = "%m/%d"), date_breaks = "2 Set labeller to adjust facet labelsc + stat_count(width = 1) x, y, | ..count.., ..prop.. weeks") - treat data values as dates.c + stat_density(adjust = 1, kernel = “gaussian") scale_*_datetime() - treat data x values as date times. t + facet_grid(. ~ fl, labeller = label_both)x, y, | ..count.., ..density.., ..scaled..e + stat_bin_2d(bins = 30, drop = T)Use same arguments as scale_x_date(). See ?strptime forlabel formats. Position Adjustments fl: c fl: d fl: e fl: p fl: rt + facet_grid(fl ~ ., labeller = label_bquote(alpha ^ .(fl)))x, y, fill | ..count.., ..density.. Position adjustments determine how to arrange geoms ↵c ↵d ↵e ↵p ↵rX & Y LOCATION SCALES that would otherwise occupy the same space.e + stat_bin_hex(bins=30) x, y, fill | ..count.., ..density.. t + facet_grid(. ~ fl, labeller = label_parsed)Use with x or y aesthetics (x shown here) c d e p re + stat_density_2d(contour = TRUE, n = 100) s <- ggplot(mpg, aes(fl, fill = drv))x, y, color, size | ..level.. scale_x_log10() - Plot x on log10 scales + geom_bar(position = "dodge")Labelse + stat_ellipse(level = 0.95, segments = 51, type = "t") scale_x_reverse() - Reverse direction of x axisscale_x_sqrt() - Plot x on square root scale Arrange elements side by sidel + stat_contour(aes(z = z)) x, y, z, order | ..level.. s + geom_bar(position = "fill")Stack elements on top of one another, t + labs( x = "New x axis label", y = "New y axis label",l + stat_summary_hex(aes(z = z), bins = 30, fun = max) COLOR AND FILL SCALES (DISCRETE) normalize heightx, y, z, fill | ..value.. title ="Add a title above the plot",n <- d + geom_bar(aes(fill = fl)) e + geom_point(position = "jitter") Use scale functionssubtitle = "Add a subtitle below title", to update legendl + stat_summary_2d(aes(z = z), bins = 30, fun = mean) Add random noise to X and Y position of eachn + scale_fill_brewer(palette = "Blues") element to avoid overplotting caption = "Add a caption below plot", labelsx, y, z, fill | ..value.. For palette choices: <aes> = "New <aes><AES> <AES> legend title")ARColorBrewer::display.brewer.all() e + geom_label(position = "nudge")f + stat_boxplot(coef = 1.5) x, y | ..lower.., B Nudge labels away from points t + annotate(geom = "text", x = 8, y = 9, label = "A")..middle.., ..upper.., ..width.. , ..ymin.., ..ymax.. n + scale_fill_grey(start = 0.2, end = 0.8,na.value = "red") geom to place manual values for geom’s aestheticsf + stat_ydensity(kernel = "gaussian", scale = “area") x, y | s + geom_bar(position = "stack")..density.., ..scaled.., ..count.., ..n.., ..violinwidth.., ..width.. Stack elements on top of one anotherCOLOR AND FILL SCALES (CONTINUOUS)e + stat_ecdf(n = 40) x, y | ..x.., ..y..e + stat_quantile(quantiles = c(0.1, 0.9), formula = y ~o <- c + geom_dotplot(aes(fill = ..x..)) Each position adjustment can be recast as a function withmanual width and height arguments Legendslog(x), method = "rq") x, y | ..quantile.. o + scale_fill_distiller(palette = "Blues") s + geom_bar(position = position_dodge(width = 1)) n + theme(legend.position = "bottom")e + stat_smooth(method = "lm", formula = y ~ x, se=T, Place legend at "bottom", "top", "left", or "right"level=0.95) x, y | ..se.., ..x.., ..y.., ..ymin.., ..ymax.. o + scale_fill_gradient(low="red", high="yellow") n + guides(fill = "none")ThemesSet legend type for each aesthetic: colorbar, legend, orggplot() + stat_function(aes(x = -3:3), n = 99, fun = o + scale_fill_gradient2(low="red", high=“blue", none (no legend)dnorm, args = list(sd=0.5)) x | ..x.., ..y.. mid = "white", midpoint = 25) n + scale_fill_discrete(name = "Title",labels = c("A", "B", "C", "D", "E"))e + stat_identity(na.rm = TRUE) r + theme_bw() r + theme_classic() Set legend title and labels with a scale function.o + scale_fill_gradientn(colours=topo.colors(6)) White backgroundggplot() + stat_qq(aes(sample=1:100), dist = qt, Also: rainbow(), heat.colors(), terrain.colors(), with grid lines r + theme_light()dparam=list(df=5)) sample, x, y | ..sample.., ..theoretical..Zoomingcm.colors(), RColorBrewer::brewer.pal() r + theme_gray() r + theme_linedraw()e + stat_sum() x, y, size | ..n.., ..prop.. Grey background(default theme) r + theme_minimal()e + stat_summary(fun.data = "mean_cl_boot") SHAPE AND SIZE SCALES Minimal themesh + stat_summary_bin(fun.y = "mean", geom = "bar") r + theme_dark() r + theme_void() Without clipping (preferred)p <- e + geom_point(aes(shape = fl, size = cyl)) dark for contrastp + scale_shape() + scale_size() Empty theme t + coord_cartesian(e + stat_unique() xlim = c(0, 100), ylim = c(10, 20))p + scale_shape_manual(values = c(3:7))With clipping (removes unseen data points)t + xlim(0, 100) + ylim(10, 20)p + scale_radius(range = c(1,6))p + scale_size_area(max_size = 6) t + scale_x_continuous(limits = c(0, 100)) +scale_y_continuous(limits = c(0, 100))RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • [email protected] • 844-448-1212 • rstudio.com • Learn more at http://ggplot2.tidyverse.org • ggplot2 2.1.0 • Updated: 2016-11Geoms - Use a geom to represent data points, use the geom’s aesthetic properties to represent variables. Each function returns a layer.Data VisualizationOne Variable Two Variableswith ggplot2 Continuous Continuous X, Continuous Y Continuous Bivariate DistributionCheat Sheet a <- ggplot(mpg, aes(hwy))f <- ggplot(mpg, aes(cty, hwy)) i <- ggplot(movies, aes(year, rating))f + geom_blank() i + geom_bin2d(binwidth = c(5, 0.5))a + geom_area(stat = "bin")(Useful for expanding limits) xmax, xmin, ymax, ymin, alpha, color, fill,Geomsx,-y,Usealpha,Data Visualization a geomcolor, fill, linetype,to represent data points,sizeuse the geom’s aesthetic properties to represent variablesOne Variableb + geom_area(aes(y = ..density..), stat = "bin") Two Variables f + geom_jitter()linetype, size, weightwith ggplot2 i + geom_density2d()GeomsContinuous a + geom_density(kernel

- Use a geom to represent Continuous = "gaussian")

X, Continuous Y Continuous Bivariate DistributionData VisualizationCheat SheetBasics a <- ggplot(mpg, aes(hwy))One Variablex, y, alpha, color, fill,datalinetype,points,f <- ggplot(mpg,f + geom_blank()use thesize,geom’saes(cty,weighthwy))aesthetic properties toTwo Variablesrepresenth <-h +x, y, alpha, color, fill,variablesggplot(movies,geom_bin2d(binwidthaes(year,=shape, sizerating))c(5, 0.5))x, y, alpha, colour, linetype, sizewith ggplot2 a + geom_area(statx, y, alpha, Continuous= "bin")b +color, fill, linetype, sizegeom_density(aes(y = ..county..))Continuous X, Continuous Y f +xmax,Continuousgeom_point()xmin, ymax, ymin, alpha, color, fill, i + geom_hex()ggplot2 is based on the grammar linetype, size,Bivariateweight DistributionCheat Sheet of graphics, the b + geom_area(aes(ya <- ggplot(mpg, a + geom_dotplot()= ..density..),aes(hwy)) stat = "bin") f <- ggplot(mpg, aes(cty, hwy))f + geom_jitter()h <- ggplot(movies, aes(year, rating))h + x, y, alpha, color, fill, shape, sizegeom_density2d() x, y, alpha, colour, fill sizeidea that you can build every graph from the same a + geom_density(kernal = "gaussian") f x,+ geom_blank()y, alpha, color, fill, shape, size hx,+y,geom_bin2d(binwidth = c(5, 0.5))alpha, colour, linetype, sizefew components: a data Basicsset, a set of geoms—visualax,+y,geom_area(stat x, y,size,alpha,= "bin")alpha, color, fill, linetype, weight color, fill xmax, xmin, ymax, ymin, alpha, color, fill,bx,+y,geom_density(aes(yalpha, color, fill, linetype, size= ..county..)) f + geom_point() hf ++ geom_quantile()linetype, size, weightgeom_hex() Continuous Functionmarks that represent data points, and a coordinate b + geom_area(aes(y = ..density..), stat = "bin")a+ geom_dotplot() f x,+ geom_jitter() hx,+y,geom_density2d()alpha, colour, fill sizesystem. F M A ax,+y,geom_density(kernal = "gaussian")y, alpha, color, fill, shape, sizex,x,y, y, alpha,colour, color, linetype, size, weight j <- ggplot(economics, aes(date, unemploy))Basicsalpha, color, fillx, y, alpha, color, fill, linetype, size, weight a + geom_freqpoly()x, y, alpha, color, fill, shape, size alpha, linetype, size4 4f + geom_quantile() Continuous Function3 3 b + geom_density(aes(y =x,..county..))a + geom_freqpoly() y, alpha, color, linetype, f x, sizecolor, linetype, size, weight+ geom_point()y, alpha, h + geom_hex() aes(date, unemploy))g <- ggplot(economics, j + geom_area()+ = a+ geom_dotplot() x, y, alpha, color, fill, shape, size gf ++ y,geom_rug(sidesx,geom_area()alpha, colour, fill size = "bl") x, y, alpha, color, fill, linetype, size2 2x, y, alpha, color, linetype,b + geom_freqpoly(aes(ysize = ..density..))x, y, alpha, color, fill f + geom_rug(sides = "bl") x,alpha, color, linetype,size size1 1F MA b + geom_freqpoly(aes(y = ..density..)) y, alpha, color, fill, linetype,a + geom_histogram(binwidth = 5)f + geom_quantile() Continuous Function4 40 0alpha, color, linetype, size0 1 2 3 4 0 1 2 3 4a + geom_histogram(binwidth = 5) g <- ggplot(economics, aes(date, unemploy))data geom coordinate plot x, y, alpha, color, linetype, size, weight j + geom_line()3 3ax,+y,geom_freqpoly() g + geom_line()x=Fy=A2system + 2= x, y, y, alpha,alpha, color, fill, linetype, size, weightalpha, color, linetype, x,size color, fill, linetype, size, weightf + geom_smooth(model = lm)fgx,+ geom_smooth(method+y,geom_area()alpha, color, linetype, size = lm)1 1 b + geom_histogram(aes(y = ..density..)) f x,+ geom_rug(sides = "bl") size, weighty, alpha, color, fill, linetype, x, y, alpha, color, fill, linetype, size x, y, alpha, color, linetype, sizeDiscrete b + geom_histogram(aes(y = ..density..))b + geom_freqpoly(aes(y = ..density..))To display data values, 0map 2 variables in2 the data set alpha, color, linetype, size g + x, y, alpha, color,= "hv") fill, linetype, size, weight0 01 3 4 0 1 3 4a + geom_histogram(binwidth = 5) geom_step(directiondata geom coordinate plot f + geom_text(aes(label = cty)) gx,+y,geom_line()to aesthetic properties ofsystemthe geom like size, color, x, y,aalpha,<- ggplot(mpg, aes(fl))size, weight alpha, color, linetype, sizeF M A x=Fy=A4 4 color, fill, linetype,b +bgeom_bar()+ geom_histogram(aes(y = ..density..))Discrete f x,+ geom_smooth(modely, label, alpha, angle, color, = lm)family, fontface, x, y, alpha, color, linetype, size j + geom_step(direction = "hv")and x and y locations. hjust, lineheight,color,size, vjust size, weightf + geom_text(aes(label = cty))3 3x, y, alpha, fill, linetype,2+ = 2 x, alpha, color, fill,Discretelinetype, size, b <- ggplot(mpg, aes(fl))weight C Visualizing errorg + geom_step(directiondf <- data.frame(grp = c("A", "B"), fit = "hv")= 4:5, se = 1:2)x, y, alpha, color, linetype, size1 1a <- ggplot(mpg, aes(fl)) f + geom_text(aes(label = cty)) AB e <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se)) family, fontface,x,x, y, y, label,alpha, color, alpha,linetype, angle,size color,F MA 040 1040 1 3 4b + geom_bar()b + geom_bar() Discrete X, Continuousx, y, label, alpha, Yangle, color, family, fontface, hjust, lineheight, size, vjustGraphical Primitives2 3 4 2data geom coordinate 3 3plot g <- ggplot(mpg,hjust, lineheight,aes(class,size, vjust hwy))x=F 2+ system = 2 x, alpha, color, fill, linetype, x, alpha,size, weightcolor, fill, linetype, size, weight e + geom_crossbar(fattenVisualizing error= 2) Visualizing errory=Acolor = F 1size = A1c <- ggplot(map, aes(long, lat))g + geom_bar(stat = "identity") df <- data.frame(grpe <- ggplot(df,x, y, ymax, ymin, = c("A",alpha, "B"), fit =fill,4:5,color,size aes(grp, fit, ymin = fit-se, ymax = fit+se))se = 1:2)linetype,df <- data.frame(grp = c("A", "B"), fit = 4:5, se = 1:2)x,Discretey, alpha, color, X, fill, linetype, ize,Continuous Y weightk <- ggplot(df, aes(grp, fit, ymin = fit-se, ymax = fit+se))0 00 1 2 3 4 0 1 2 3 4c + geom_polygon(aes(groupGraphical Primitives= group)) g <- ggplot(mpg, aes(class, hwy)) e + geom_errorbar()data geom coordinatesystemplotx, y, alpha, color, fill, linetype, size g + geom_boxplot() Discreteex,+ymax, ymin, alpha,X,geom_crossbar(fatten Continuouscolor, = 2)linetype, size, YGraphical Primitivesx=Fy=A glower,+ geom_bar(statmiddle, upper,=x,"identity")ymax, ymin, alpha, gwidthx, <- ggplot(mpg,(alsoy, ymax, alpha, color,aes(class,geom_errorbarh())ymin, fill, linetype, hwy))color = Fsize = A c <- ggplot(map, aes(long, lat)) color, fill, linetype,x, y, alpha, shape,color, fill, size, size,linetype, weightweight e +sizegeom_linerange() k + geom_crossbar(fatten = 2)c + geom_polygon(aes(group = group)) g + geom_dotplot(binaxis = "y", ex,+ymin,geom_errorbar()ymax, alpha, color, linetype, sizeBuild a graph with ggplot() or qplot() g <- ggplot(economics, aes(date, unemploy))x, y, alpha, color, fill, linetype, sizemap <- map_data("state")gstackdir+ geom_boxplot()= "center") g x,+ymax, geom_bar(statymin, alpha, color, linetype, = "identity")size, x, y, ymax, ymin, alpha, color, fill, linetype,g + geom_path(lineend="butt", c <- ggplot(map, aes(long, x,lower,y, alpha, lat))color,middle, fill x, ymax, ymin, alpha,upper, e +width (also geom_errorbarh())geom_pointrange() sizelinejoin="round’, linemitre=1) g +color, fill, linetype, shape,geom_violin(scale size, weight= "area") ex,+x, y, alpha,y,geom_linerange()ymin, ymax, alpha,color,color,fill, linetype, size, weightfill, linetype,ggplot(data = mpg, aes(x = cty, y = hwy)) x, y, alpha, color, linetype, c + geom_polygon(aes(groupsize =gx,+y,geom_dotplot(binaxisalpha, color, group))fill, linetype, =size,"y", weight shape,x, ymin,sizeymax, alpha, color, linetype, size k + geom_errorbar()g <- ggplot(economics, aes(date, unemploy))Begins a plotF M thatA you finish by adding layers to. No g + geom_ribbon(aes(ymin=unemploy - 900, stackdir = "center") g +geom_pointrange()geom_boxplot() x, ymax, ymin, alpha, color, linetype, size,+ 900)) x, y, alpha, color, fill, linetype, sizefill4 4Mapsgymax=unemploy+ geom_path(lineend="butt", x, y, alpha, color, data e<-+data.frame(murder = USArrests$Murder,defaults, but provides more3control2 than qplot().3x,linejoin="round’ymax, ymin, alpha, , linemitre=1)color, fill, linetype, size g + geom_violin(scale = "area") statex,=lower, middle, upper,y,tolower(rownames(USArrests)))ymin, ymax, alpha, color, x, ymax, ymin, alpha,fill, linetype, width (also geom_errorbarh())2+ = Discrete X, Discrete Ymap <- shape, sizemap_data("state")data 1 1 x, y, alpha, color, linetype, sizeg + geom_ribbon(aes(ymin=unemploy - 900,h <-x,ggplot(diamonds,y, alpha, color, fill, linetype,aes(cut, size, weightcolor)) color,e <- ggplot(data, fill, linetype,aes(fill = murder)) shape, size, weight k + geom_linerange()F MA 04 04 add layers, d<- e + geom_map(aes(map_id Maps = state), map = map) +elements with + x,ymax=unemployggplot(seals, aes(x + 900)= long,) y = lat)) h + geom_jitter() datag<-+ geom_dotplot(binaxis = USArrests$Murder, = "y", x, ymin, ymax, alpha, color, linetype, size0 1 3 4 0 1 2 3 4data geom 3 coordinate2plot data.frame(murderexpand_limits( x = map$long, y = map$lat)3ggplot(mpg, aes(hwy,+ cty))system = + ymax, ymin,d + geom_segment(aes( d <- ggplot(economics, aes(date,alpha, color, fill, linetype, size x, y, alpha,Discrete unemploy))color, fill, shape,X, Discrete Y size state = tolower(rownames(USArrests)))<-stackdir = "center")x=F 2 2y=A mapmap_id, alpha, color, fill, linetype, sizemap_data("state")geom_point(aes(color = cyl)) 1 + layer = geom + xend = long + delta_long, h <- ggplot(diamonds, aes(cut, color)) e <- ggplot(data, aes(fill = murder))k + geom_pointrange()1ggplot(seals, aes(x dgeom_smooth(method 0 ="lm") + 0 0 1 2 default stat + d<-yend = lat + delta_lat)) + geom_path(lineend="butt", Three Variables e + x, y,geom_map(alpha, color,= state),aes(map_id fill map = map) += long, y = lat)) h + geom_jitter()plotlayer specific x, xend, y, yend, alpha, color,0 1 2 3 4 3 4linetype, sizecoord_cartesian()data geom + coordinatex=F system mappings dd++geom_rect(aes(xmin linejoin="round’geom_segment(aes(= long, ymin = lat,, linemitre=1)seals$z x, y, alpha, color,<- with(seals, fill, shape, size+ delta_lat^2))sqrt(delta_long^2 expand_limits(gi map_id,++ geom_violin(scalegeom_raster(aes(fillx = map$long, = map$lat)= z),yhjust=0.5, = "area") x, y, ymin, ymax, alpha, color, fill, linetype,scale_color_gradient() y=A + vjust=0.5,alpha, color, fill, linetype, sizeinterpolate=FALSE) shape, sizetheme_bw()xend =longxmax= long++delta_long,delta_long, x, y, alpha, color,ilinetype,<- ggplot(seals,sizeaes(long, lat))x, y, alpha, color, fill, linetype, size, weightadditional ymax yend == lat lat ++ delta_lat))delta_lat)) Three Variables x, y, alpha, fillelements x, xend, y, yend, alpha, d +color, geom_ribbon(xmax, xmin, ymax, ymin, alpha, color, fill,linetype, size aes(ymin=unemployi + geom_contour(aes(z = z)) - 900, i + geom_tile(aes(fill = z))i +x, geom_raster(aes(fill = z),sizehjust=0.5, Mapsseals$z <-x,with(seals,y, z, alpha, sqrt(delta_long^2 + delta_lat^2))Add a new layer to a plot with a geom_*() dlinetype, size+ geom_rect(aes(xmin ymax=unemploy= long, ymin = lat, + 900) ) colour, linetype, size,i <- ggplot(seals, aes(long, lat))weight y, alpha, color, fill, linetype,vjust=0.5, interpolate=FALSE) data <- data.frame(murder = USArrests$Murder,xmax= long + delta_long, x, ymax, ymin, alpha, color, fill, linetype, size x, y, alpha, fill state = tolower(rownames(USArrests)))or stat_*()RStudio® is afunction.trademark of RStudio, Each Inc. • provides a geom, a• 844-448-1212ymaxCC BY RStudio • [email protected] = lat + delta_lat))

• rstudio.com Discrete

Learn more at docs.ggplot2.org X, 0.9.3.1

• ggplot2 Discrete • Updated: 3/15Y

xmax, xmin, ymax, ymin, alpha, color, fill,i + geom_contour(aes(z = z)) i + geom_tile(aes(fill = z)) map <- map_data("state")set of aesthetic mappings, and a default stat linetype, size x, y, z, alpha, colour, linetype, size, weight h <-x, ggplot(diamonds,y, alpha, color, fill, linetype, size aes(cut, color)) l <- ggplot(data, aes(fill = murder))and position adjustment. l + geom_map(aes(map_id = state), map = map) +RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • [email protected] • 844-448-1212 • rstudio.com e <- ggplot(seals, aes(x = long, y = lat)) h + geom_jitter()Learn more at docs.ggplot2.org • ggplot2 0.9.3.1 • Updated: 3/15aesthetic mappings data geom x, y, alpha, color, fill, shape, size expand_limits(x = map$long, y = map$lat)e + geom_segment(aes( map_id, alpha, color, fill, linetype, sizeqplot(x = cty, y = hwy, color = cyl, data = mpg, geom = "point") xend = long + delta_long,Creates a complete plot with given data, geom, and yend = lat + delta_lat))mappings. Supplies many useful defaults. Three Variablesx, xend, y, yend, alpha, color, linetype, sizeseals$z <- with(seals, sqrt(delta_long^2 + delta_lat^2)) m + geom_raster(aes(fill = z), hjust=0.5,last_plot() e + geom_rect(aes(xmin = long, ymin = lat, m <- ggplot(seals, aes(long, lat)) vjust=0.5, interpolate=FALSE)Returns the last plot xmax= long + delta_long,ymax = lat + delta_lat)) x, y, alpha, fill (fast)ggsave("plot.png", width = 5, height = 5) m + geom_contour(aes(z = z)) m + geom_tile(aes(fill = z))Saves last plot as 5’ x 5’ file named "plot.png" in xmax, xmin, ymax, ymin, alpha, color, fill,linetype, size x, y, z, alpha, colour, linetype, size, weight x, y, alpha, color, fill, linetype, size (slow)working directory. Matches file type to file extension.RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • [email protected] • 844-448-1212 • rstudio.com Learn more at docs.ggplot2.org • ggplot2 1.0.0 • Updated: 4/15Stats - An alternative way to build a layer Scales Coordinate Systems FacetingScales control how a plot maps data values to the visual Facets divide a plot into subplots based on the valuesSome plots visualize a transformation of the original data set. r <- b + geom_bar()Use a stat to choose a common transformation to visualize, values of an aesthetic. To change the mapping, add a of one or more discrete variables.e.g. a + geom_bar(stat = "bin")r + coord_cartesian(xlim = c(0, 5)) t <- ggplot(mpg, aes(cty, hwy)) + geom_point()custom scale.fl cty cyl n <- b + geom_bar(aes(fill = fl)) xlim, ylimt + facet_grid(. ~ fl)4 4x ..count.. 3 3n The default cartesian coordinate system+ 2= 2facet into columns based on fl1 1aesthetic prepackaged scale specific r + coord_fixed(ratio = 1/2)0 00 1scale_to adjust scale to use arguments ratio, xlim, ylimt + facet_grid(year ~ .)facet into rows based on year0 1 2 3 4 2 3 4data stat geom coordinate plotx=x system n + scale_fill_manual( Cartesian coordinates with fixed aspectt + facet_grid(year ~ fl)y = ..count..Each stat creates additional variables to map aesthetics values = c("skyblue", "royalblue", "blue", "navy"), ratio between x and y unitslimits = c("d", "e", "p", "r"), breaks =c("d", "e", "p", "r"),facet into both rows and columnsto. These variables use a common ..name.. syntax. r + coord_flip()name = "fuel", labels = c("D", "E", "P", "R")) t + facet_wrap(~ fl)stat functions and geom functions both combine a stat xlim, ylim wrap facets into a rectangular layoutwith a geom to make a layer, i.e. stat_bin(geom="bar") range of values to title to use in labels to use in breaks to use in Flipped Cartesian coordinatesdoes the same as geom_bar(stat="bin") include in mapping legend/axis legend/axis legend/axisr + coord_polar(theta = "x", direction=1 ) Set scales to let axis limits vary across facetslayer specific variable created theta, start, direction t + facet_grid(y ~ x, scales = "free")stat function mappings by transformation General Purpose scalesPolar coordinates x and y axis limits adjust to individual facetsUse with any aesthetic:

i + stat_density2d(aes(fill = ..level..), alpha, color, fill, linetype, shape, size r + coord_trans(ytrans = "sqrt") • "free_x" - x axis limits adjustgeom = "polygon", n = 100) xtrans, ytrans, limx, limy • "free_y" - y axis limits adjustscale_*_continuous() - map cont’ values to visual valuesgeom for layer parameters for stat scale_*_discrete() - map discrete values to visual values Transformed cartesian coordinates. Setxtrans and ytrans to the name Set labeller to adjust facet labelsa + stat_bin(binwidth = 1, origin = 10) scale_*_identity() - use data values as visual values of a window function.1D distributions t + facet_grid(. ~ fl, labeller = label_both)x, y | ..count.., ..ncount.., ..density.., ..ndensity.. scale_*_manual(values = c()) - map discrete values to60a + stat_bindot(binwidth = 1, binaxis = "x") manually chosen visual values z + coord_map(projection = "ortho", fl: c fl: d fl: e fl: p fl: rorientation=c(41, -74, 0))latx, y, | ..count.., ..ncount.. t + facet_grid(. ~ fl, labeller = label_bquote(alpha ^ .(x)))a + stat_density(adjust = 1, kernel = "gaussian") X and Y location scales projection, orientation, xlim, ylim ↵c ↵d ↵e ↵p ↵rx, y, | ..count.., ..density.., ..scaled.. Use with x or y aesthetics (x shown here) Map projections from the mapproj package long t + facet_grid(. ~ fl, labeller = label_parsed)f + stat_bin2d(bins = 30, drop = TRUE) scale_x_date(labels = date_format("%m/%d"), (mercator (default), azequalarea, lagrange, etc.) c d e p r2D distributionsx, y, fill | ..count.., ..density.. breaks = date_breaks("2 weeks")) - treat xf + stat_binhex(bins = 30) values as dates. See ?strptime for label formats.x, y, fill | ..count.., ..density.. Position Adjustments Labelsscale_x_datetime() - treat x values as date times. Usef + stat_density2d(contour = TRUE, n = 100)same arguments as scale_x_date(). Position adjustments determine how to arrange t + ggtitle("New Plot Title")x, y, color, size | ..level..scale_x_log10() - Plot x on log10 scale geoms that would otherwise occupy the same space. Add a main title above the plotm + stat_contour(aes(z = z)) 3 Variables scale_x_reverse() - Reverse direction of x axis s <- ggplot(mpg, aes(fl, fill = drv)) t + xlab("New X label") Use scale functionsx, y, z, order | ..level.. to update legends + geom_bar(position = "dodge") Change the label on the X axism+ stat_spoke(aes(radius= z, angle = z)) scale_x_sqrt() - Plot x on square root scale labelsangle, radius, x, xend, y, yend | ..x.., ..xend.., ..y.., ..yend.. Arrange elements side by side t + ylab("New Y label")m + stat_summary_hex(aes(z = z), bins = 30, fun = mean) Color and fill scales Change the label on the Y axisx, y, z, fill | ..value.. Discrete Continuous s + geom_bar(position = "fill") t + labs(title =" New title", x = "New x", y = "New y")m + stat_summary2d(aes(z = z), bins = 30, fun = mean) Stack elements on top of one another,x, y, z, fill | ..value.. n <- b + geom_bar( o <- a + geom_dotplot( All of the aboveaes(fill = fl)) aes(fill = ..x..))normalize heightg + stat_boxplot(coef = 1.5) Comparisons n + scale_fill_brewer( o + scale_fill_gradient( s + geom_bar(position = "stack") Legendsx, y | ..lower.., ..middle.., ..upper.., ..outliers.. palette = "Blues") low = "red",For palette choices: high = "yellow") Stack elements on top of one another t + theme(legend.position = "bottom")g + stat_ydensity(adjust = 1, kernel = "gaussian", scale = "area") o + scale_fill_gradient2(library(RColorBrewer) Place legend at "bottom", "top", "left", or "right"x, y | ..density.., ..scaled.., ..count.., ..n.., ..violinwidth.., ..width.. display.brewer.all() low = "red", high = "blue", f + geom_point(position = "jitter")mid = "white", midpoint = 25)f + stat_ecdf(n = 40) n + scale_fill_grey( o + scale_fill_gradientn( Add random noise to X and Y position t + guides(color = "none")Functionsx, y | ..x.., ..y.. start = 0.2, end = 0.8, colours = terrain.colors(6)) of each element to avoid overplotting Set legend type for each aesthetic: colorbar, legend,na.value = "red") Also: rainbow(), heat.colors(),f + stat_quantile(quantiles = c(0.25, 0.5, 0.75), formula = y ~ log(x), or none (no legend)method = "rq")topo.colors(), cm.colors(), Each position adjustment can be recast as a functionRColorBrewer::brewer.pal() with manual width and height arguments t + scale_fill_discrete(name = "Title",x, y | ..quantile.., ..x.., ..y..labels = c("A", "B", "C"))f + stat_smooth(method = "auto", formula = y ~ x, se = TRUE, n = 80, Shape scales Manual Shape valuesManual shape valuess + geom_bar(position = position_dodge(width = 1)) Set legend title and labels with a scale function.fullrange = FALSE, level = 0.95)x, y | ..se.., ..x.., ..y.., ..ymin.., ..ymax.. p <- f + geom_point(aes(shape = fl))0 6 12 18 24 00ggplot() + stat_function(aes(x = -3:3), 1 7 13 19 25 ++ Themes ZoomingGeneral Purpose p + scale_shape(fun = dnorm, n = 101, args = list(sd=0.5))x | ..y..solid = FALSE) 2 8 14 20 ** -| - r + theme_bw() 150r + theme_classic()Without clipping (preferred)|1503 9 15 21 . 100t + coord_cartesian(countp + scale_shape_manual( White background100countf + stat_identity() White backgroundoo xlim = c(0, 100), ylim = c(10, 20))50%50values = c(3:7)) 4 10 16 22 %with grid lines0no gridlinesggplot() + stat_qq(aes(sample=1:100), distribution = qt,0c d e p rc d e p rShape values shown infl fldparams = list(df=5)) chart on right5 11 17 23 OO ## 150 r + theme_grey() 150r + theme_minimal() With clipping (removes unseen data points)sample, x, y | ..x.., ..y.. Grey background Minimal theme100 100countcountt + xlim(0, 100) + ylim(10, 20)50 50f + stat_sum() Size scales 0c d e p r(default theme) 0c d e p rt + scale_x_continuous(limits = c(0, 100)) +fl flx, y, size | ..size.. q + scale_size_area(max = 6)f + stat_summary(fun.data = "mean_cl_boot") q <- f + geom_point( Value mapped to area of circle ggthemes - Package with additional ggplot2 themes scale_y_continuous(limits = c(0, 100))aes(size = cyl)) (not radius)f + stat_unique()RStudio® is a trademark of RStudio, Inc. • CC BY RStudio • [email protected] • 844-448-1212 • rstudio.com Learn more at docs.ggplot2.org • ggplot2 1.0.0 • Updated: 4/15

← 返回批次1总导航