【发布时间】:2026-01-22 11:55:01
【问题描述】:
我有一个带有多个可选参数的函数来使用 ggplot2 修改绘图。如果缺少这些参数中的任何一个,我想在 ggplot2 中使用它们的默认值。如果只有一个参数,可以这样做:
simple_plot <- function (color) {
p <- ggplot(mtcars, aes(cyl, mpg))
if(!missing(color))
{
p <- p + geom_point(col = color)
} else {
p <- p + geom_point() # use its default if the argument is missing
}
}
但是,当有多个参数来修改绘图的点形状、填充、轴标题、中断、限制等时,这不是一个好的解决方案。有没有更好的方法?
[编辑以澄清我的问题]
感谢那些回答我问题的人。我想通过包含以下代码来澄清我的问题。将调用多个函数,并且每个函数都有多个参数。使用do.call 似乎不是一种简单的实现方式。
better_plot <- function(col.y1, shape.y1, col.y2, shape.y2,
title.y1, breaks.y1, title.y2, breaks.y2, title){
p <- ggplot(mtcars, aes(x = cyl)) +
# 1st y data points
case_when(
missing(col.y1) & missing(shape.y1) ~ geom_point(aes(y = mpg)),
missing(col.y1) & !missing(shape.y1) ~ geom_point(aes(y = mpg), shape = shape.y1),
!missing(col.y1) & missing(shape.y1) ~ geom_point(aes(y = mpg), col = col.y1),
!missing(col.y1) & !missing(shape.y1) ~ geom_point(aes(y = mpg), col = col.y1, shape = shape.y1)
) +
# 2nd y data points
case_when(
missing(col.y2) & missing(shape.y2) ~ geom_point(aes(y = hp)),
missing(col.y2) & !missing(shape.y2) ~ geom_point(aes(y = hp), shape = shape.y2),
!missing(col.y2) & missing(shape.y2) ~ geom_point(aes(y = hp), col = col.y2),
!missing(col.y2) & !missing(shape.y2) ~ geom_point(aes(y = hp), col = col.y2, shape = shape.y2)
) +
# y axises - labels and breaks
case_when(
!missing(title.y1) & !missing(breaks.y1) & !missing(title.y2) & !missing(breaks.y2) ~
scale_y_continuous(
name = title.y1, breaks = breaks.y1,
sec.axis = sec_axis(name = title.y2, breaks = breaks.y2)),
!missing(title.y1) & !missing(breaks.y1) & !missing(title.y2) & missing(breaks.y2) ~
scale_y_continuous(
name = title.y1, breaks = breaks.y1,
sec.axis = sec_axis(name = title.y2)),
!missing(title.y1) & !missing(breaks.y1) & missing(title.y2) & missing(breaks.y2) ~
scale_y_continuous(
name = title.y1, breaks = breaks.y1),
.... # the remaining combinations...
)
# add plot title if any
if(!missing(title)) p <- p + ggtitle(title)
return(p)
}
【问题讨论】:
-
所以您希望将命名参数分配给不同的函数,例如
ggplot、geom_point、scale_x_continuous等? -
是的。例如,title.x 和 title.y 用于轴标题。如果缺少这些参数中的任何一个,则轴标题将由 ggplot2 分配,默认情况下是 x 和 y 变量的名称。