且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用循环功能在同一张图上创建多个ggboxplots?

更新时间:2023-08-30 13:07:46

您可以使用 Map 创建地块列表,并使用 ggarrange 进行绘制.分别传递列名和y标签.

You can use Map to create list of plots and use ggarrange to plot it. Pass column names and y-labels separately.

library(ggpubr)

cols <- setdiff(names(tg_proposer_split), 'round_type')
y_labels <- c("Offer (by A)", "Amount Transferred by Partner (Bot)", "Payoff (for A)")

Map(function(x, y) {
  ggboxplot(data = tg_proposer_split, x = "round_type", y = x,
            fill = "round_type",
            palette = "ucscgb",
            ylab = y, xlab = "Round Type",
            add = "jitter",
            shape = "round_type")
}, cols, y_labels) -> list_plots

ggarrange(plotlist = list_plots, common.legend = TRUE)

数据

tg_proposer_split <- structure(list(offer = c(40L, 100L,0L,100L, 25L, 80L,100L, 
0L, 25L, 100L), payoff = c(126L, 273L, 100L, 6L, 99L, 29L, 45L, 
100L, 99L, 183L), partner_transfer = c(66L, 273L, 0L, 6L, 24L, 
9L, 45L, 0L, 24L, 183L), round_type = c("actual", "actual", "actual", 
"actual", "actual", "practice", "practice", "practice", "practice", 
"practice")), class = "data.frame", row.names = c(NA, -10L))