【问题标题】:properly formatting a two-line caption in ggplot2在 ggplot2 中正确格式化两行标题
【发布时间】:2019-01-29 06:52:27
【问题描述】:

我正在开发一个自定义函数,该函数可以为绘图添加两行标题,并且无论用户可能选择输入什么("character""expression"),我都希望标题的格式正确。我在下面创建了一个玩具示例来说明该功能当前实现方式的两个问题-

  1. 当标题不是NULL时,两行不对齐 正确的。
  2. 当输入一个表达式时,连接的标题得到完全 损坏。

编辑:

如果您有不同的解决方案来实现相同的目标(如果用户提供的 captionNULL,则默认的单行表达式将打印为标题,否则将两行表达式打印为一个标题),我也对此持开放态度。

重要虽然对象的类仍然是 "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 package (v0.2.0.9000) 于 2018 年 8 月 22 日创建。

【问题讨论】:

  • 是的,使用atop 效果很好,但它确实使文本居中,而不是右对齐。顺便说一句,这是因为不支持多行表达式。
  • @mike-badescu,正如 Axeman 所说,该解决方案对我不起作用,因为这两行的格式仍然不符合我的喜好。

标签: r ggplot2 label plotmath


【解决方案1】:

这个怎么样:

# 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"))
)

我从这个question 得到了atop 的想法

【讨论】:

  • 哇哦!非常感谢!
  • 再想一想,这实际上不是我想要的:你将caption 变成xlab,但这意味着函数plot_makerxlab 参数将不再工作。例如,尝试-plot_maker( caption = substitute(paste(italic("Note"), ": This is mtcars dataset")), xlab = "xlabel", ylab = "ylabel" ) ,您将看到"xlabel" 无处出现。
  • 对。我已经编辑了我的答案以允许标题和 xlab
【解决方案2】:

调整链接问题的答案,

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()))

【讨论】:

  • 嗨。欢迎来到 StackOverflow 并感谢您的回答。您能否提供一个reprex (github.com/tidyverse/reprex) 以及我在我的问题中包含的示例?这将有助于确定代码是否在指定的情况下工作。谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多