r - 如何在同一张图上创建多个图(图均值)?
问题描述
TL;DR:尝试使用循环功能在一张图中创建多个图(附图片)。目前为每个箱线图手动创建代码,然后使用par()
函数将它们绘制在一起。它有效,但正在寻找一种重复性较低的方式。
我想知道是否可以创建多个图;专门绘制“情节手段”。您可以在此处找到图像形式的确切输出(关于绘图的第二个示例意味着):如何使用循环函数在同一个图上创建多个 ggboxplots?
我的数据看起来像这样:
# A tibble: 62 x 4
offer payoff partner_transfer round_type
<dbl> <dbl> <dbl> <chr>
1 40 126 66 actual
2 100 273 273 actual
3 0 100 0 actual
4 100 6 6 actual
5 25 99 24 actual
6 80 29 9 practice
7 100 45 45 practice
8 0 100 0 practice
9 25 99 24 practice
10 100 183 183 practice
# ... with 52 more rows
我试图让它看起来像这样:
![样本图表示][2]
目前,我获取此输出的代码是:
par(mfrow = c(2,2))
plot_offer <- plotmeans( offer ~ round_type, data = tg_proposer_split,
xlab = "Round Type", ylab = "Offer (by A)",
main="Mean Plot with 95% CI")
plot_partner_transfer <- plotmeans( partner_transfer ~ round_type, data = tg_proposer_split,
xlab = "Round Type", ylab = "Amount Transferred by Partner (Bot)",
main="Mean Plot with 95% CI")
plot_payoff <- plotmeans( payoff ~ round_type, data = tg_proposer_split,
xlab = "Round Type", ylab = "Payoff (for A)",
main="Mean Plot with 95% CI")
有没有办法缩短这段代码?
最大的歉意,由于某种原因我无法附加图像,因为我没有整理足够的声誉点,所以我别无选择,只能这样尝试。希望它仍然清楚。
非常感谢!
解决方案
这是一种简化代码的方法Map
。
- 定义一个通用函数来处理绘图,
fun_plot
; - 获取y轴变量的列名;
- 创建一个 y 轴标签的向量;
Map
循环绘制。
代码变成
fun_plot <- function(ycol, ylab){
fmla <- paste(ycol, "round_type", sep = "~")
fmla <- as.formula(fmla)
plotmeans(fmla, data = tg_proposer_split,
xlab = "Round Type", ylab = ylab,
main = "Mean Plot with 95% CI")
}
y_cols <- names(tg_proposer_split)[which(names(tg_proposer_split) != "round_type")]
y_lab <- c("Offer (by A)", "Amount Transferred by Partner (Bot)", "Payoff (for A)")
old_par <- par(mfrow = c(2,2))
Map(fun_plot, y_cols, y_lab)
par(old_par)
编辑。
在评论中报告的错误之后,这里有一个更通用的函数,允许xcol
和 数据集分别取任何值,而不仅仅是"round_type"
和tg_proposer_split
。此解决方案现在使用mapply
, not Map
,以便将这两个参数传递到MoreArgs
列表中。
fun_plot2 <- function(ycol, ylab, xcol, data){
fmla <- paste(ycol, xcol, sep = "~")
fmla <- as.formula(fmla)
plotmeans(fmla, data = data,
xlab = "Round Type", ylab = ylab,
main = "Mean Plot with 95% CI")
}
old_par <- par(mfrow = c(2,2))
mapply(fun_plot2, y_cols, y_lab,
MoreArgs = list(
xcol = "round_type",
data = tg_proposer_split
)
)
par(old_par)
数据
tg_proposer_split <- read.table(text = "
offer payoff partner_transfer round_type
1 40 126 66 actual
2 100 273 273 actual
3 0 100 0 actual
4 100 6 6 actual
5 25 99 24 actual
6 80 29 9 practice
7 100 45 45 practice
8 0 100 0 practice
9 25 99 24 practice
10 100 183 183 practice
", header = TRUE)
推荐阅读
- opencv - AttributeError 'NoneType' 对象没有属性 'shape'
- angular-material - 如何在 Angular Material 中创建类似于 bootstrap 的网格布局系统?
- android - 约束布局 - 如何使图像视图(框架)在整个屏幕上移动
- sql - 如何将不同类型的值插入表中的列?
- amazon-web-services - 有没有办法在不使用额外的 AWS Lambda 来检查授权的情况下将 S3 Bucket 与 Appsync 集成?
- python - 我的代码在 python shell 中运行良好,但在我的 Visual Studio 代码上运行时没有显示任何内容
- php - Laravel DD api 不显示完整数组
- javascript - 二进制搜索中开始结束索引的混淆
- twilio - 使用 API 或 HTTP POST 编辑 Twilio TwiML
- c++ - 如何在 OMNeT++ 中使用 NetworKit 作为库?