Ind*_*til 12 label r ggplot2 plotmath
我正在开发一个自定义函数,可以为图表添加两行字幕,我希望无论用户可能选择输入("character"或"expression"),都可以正确格式化标题.我在下面创建了一个玩具示例,以说明当前实现该功能的两个问题 -
NULL,两条线不对齐.编辑:
如果你有一个不同的解决方案实现相同的东西(如果用户提供的caption是NULL,那么默认的单行表达式打印为标题,否则打印为标题的两行表达式),我也愿意那.
尽管对象的类仍然存在是很重要的,"ggplot"因为我想使用ggplot2函数对结果图进行进一步修改.
# needed libraries
library(ggplot2)
# custom function to prepare a caption
caption_maker <- function(caption) {
# if caption is not null then add line separator
if (!is.null(caption)) {
caption <- paste(caption, "; \n", sep = "")
}
# prepare the caption with additional info
caption <- base::substitute(
expr =
paste(
y,
"In favor of null: ",
"log"["e"],
"(BF"["01"],
") = ",
bf
),
env = base::list(
y = caption,
bf = 123
)
)
# return the message
return(caption)
}
# custom function to add labels to the plot
plot_maker <-
function(xlab = NULL,
ylab = NULL,
title = NULL,
caption = NULL) {
caption.text <- caption_maker(caption = caption)
plot <- ggplot(mtcars, aes(wt, mpg)) + geom_point() +
ggplot2::labs(
x = xlab,
y = ylab,
title = title,
caption = caption.text
)
# return the plot
return(plot)
}
# this works just fine
plot_maker(caption = NULL)
Run Code Online (Sandbox Code Playgroud)

# this works but the caption is not aligned properly
plot_maker(caption = "This is mtcars dataset")
Run Code Online (Sandbox Code Playgroud)

# this works but the caption is all mangled
plot_maker(
caption =
expression(paste(italic("Note"), ": This is mtcars dataset"))
)
Run Code Online (Sandbox Code Playgroud)

由reprex包创建于2018-08-22 (v0.2.0.9000).
这个怎么样:
# needed libraries
library(ggplot2)
# custom function to prepare a caption
caption_maker <- function(caption) {
# prepare the caption with additional info
caption <- base::substitute(
atop(y,
paste(
"In favor of null: ",
"log"["e"],
"(BF"["01"],
") = ",
bf
)),
env = base::list(
bf = 123,
y = caption
)
)
# return the message
return(caption)
}
# custom function to add labels to the plot
plot_maker <-
function(xlab = NULL,
ylab = NULL,
title = NULL,
caption = NULL) {
caption.text <- caption_maker(caption = caption)
plot <- ggplot(mtcars, aes(wt, mpg)) + geom_point() +
ggplot2::labs(
x = xlab,
y = ylab,
title = title,
caption = caption.text)
# return the plot
return(plot)
}
plot_maker(caption = NULL)
plot_maker(caption = "This is mtcars:")
plot_maker(xlab = "x Axis Title",
caption = substitute(paste(italic("Note"), ": This is mtcars dataset"))
)
Run Code Online (Sandbox Code Playgroud)
我atop从这个问题得到了这个想法