r - 在 ggplot2 中正确格式化两行标题
问题描述
我正在开发一个自定义函数,该函数可以在绘图中添加两行标题,并且无论用户可能选择输入什么("character"
或"expression"
),我都希望标题的格式正确。我在下面创建了一个玩具示例来说明该功能当前实现方式的两个问题-
- 当标题为 not
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)
# this works but the caption is not aligned properly
plot_maker(caption = "This is mtcars dataset")
# this works but the caption is all mangled
plot_maker(
caption =
expression(paste(italic("Note"), ": This is mtcars dataset"))
)
由reprex 包(v0.2.0.9000)于 2018 年 8 月 22 日创建。
解决方案
调整链接问题的答案,
library(gridExtra)
library(grid)
library(ggplot2)
element_custom <- function() {
structure(list(), class = c("element_custom", "element_text"))
}
element_grob.element_custom <- function(element, label="", ...) {
mytheme <- ttheme_minimal(core = list(fg_params = list(parse=TRUE,
hjust=0, x=0)))
disect <- strsplit(label, "\\n")[[1]]
tg <- tableGrob(as.matrix(disect), theme=mytheme)
tg$vp = viewport(just=1,x=1, width = sum(tg$widths))
tg
}
heightDetails.gtable <- function(x) sum(x$heights)
ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
geom_line() +
labs(x= "italic('Note')*': this is mtcars'\n 'in favour of null: '*log[10](bf['01'])=='123'")+
(theme_grey() %+replace% theme(axis.title.x = element_custom()))
推荐阅读
- reactjs - 如何让 React 输入文本并选择?
- matrix - 倾斜/倾斜纹理 - Monogame
- c# - C#,“复合组件”/用户控件
- python - 搜索两个数据框以了解变量何时在同一行相遇
- docker - 同一个 Docker 层怎么会有不同的大小?
- excel - 从 Windows 服务应用程序运行 Excel 宏时出错
- kubernetes-helm - Helm模板 - 如何在数组中使用“如果至少存在一个”?
- python - Python重新查找所有匹配的重复模式
- ruby - 用于 Sed 命令的 Ruby Escape 反斜杠
- javascript - Ajax/jQuery 脚本如何在一个表单 url 中显示 2+ 个相关的下拉框条目?