rmarkdown
您可以使用 chunk 参数在文档中并排输出数字fig.show='hold'
。另一种选择是用于ggplot2
创建绘图,而不是cars
scatterplot
函数。我在下面展示了这两种方法。
文档中的并排cars::scatterplot
图rmarkdown
以下是 PDF 输出的示例。设置输出文档中每个绘图的实际大小,与和out.width='3in'
无关。但是您仍然可以调整和调整相对于绘图区域的纵横比和文本大小。fig.height
fig.width
fig.height
fig.width
---
title: "Untitled"
author: "eipi10"
date: "November 23, 2016"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r fig.show='hold', out.width='3in', fig.height=5, fig.width=5}
library(car)
scatterplot(Sepal.Length~Sepal.Width|Species,data=iris,grid="FALSE",
boxplots="", reg.line="FALSE", pch=c(0,1,2))
scatterplot(Petal.Width~Sepal.Width|Species,data=iris,grid="FALSE",
boxplots="", reg.line="FALSE", pch=c(0,1,2))
```
并排散点图使用ggplot2
如果您愿意,ggplot2
那么您可以相对轻松地获得两个情节布局:
library(ggplot2)
library(gridExtra)
theme_set(theme_bw())
grid.arrange(
ggplot(iris, aes(Sepal.Width, Sepal.Length, colour=Species)) +
geom_point() +
geom_smooth(alpha=0.2) +
theme(legend.position="top"),
ggplot(iris, aes(Sepal.Width, Petal.Width, colour=Species)) +
geom_point() +
geom_smooth(alpha=0.2) +
theme(legend.position="top"),
ncol=2)
自定义ggplot2
绘图以看起来更像cars::scatterplot
输出
您可以通过其他方式自定义上面的代码。如果您不想要置信区间,请添加se=FALSE
到geom_smooth
. 如果您希望每个物种有不同的形状,请添加aes(shape=Species)
到geom_point
. 如果您想要基本图形中使用的特定形状,请添加+ scale_shape_manual(values=0:2)
等。您还可以通过一些额外的工作获得单个图例。
在下面的代码中,我添加了这些和其他自定义项,以重现更接近原始基本图形的内容。
# Components we'll reuse for both plots
my_theme = list(geom_point(aes(shape=Species)),
geom_smooth(se=FALSE, show.legend=FALSE, lwd=0.8),
scale_shape_manual(values=0:2),
scale_colour_manual(values=c("black", "red","green")),
theme_bw(),
theme(panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
legend.position="top"))
p1 = ggplot(iris, aes(Sepal.Width, Sepal.Length, colour=Species)) +
my_theme +
labs(x="Sepal Width", y="Sepal Length") +
scale_y_continuous(limits=c(3,8)) +
scale_x_continuous(limits=c(1,5))
p2 = ggplot(iris, aes(Sepal.Width, Petal.Width, colour=Species)) +
my_theme +
labs(x="Sepal Width", y="Petal Width")
# Function to extract legend
# https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
leg = g_legend(p1)
grid.arrange(leg,
arrangeGrob(grobs=lapply(list(p1,p2), function(p) p + guides(colour=FALSE, shape=FALSE)), ncol=2),
ncol=1, heights=c(1,10))