【问题标题】:Equal spacing with multiple atop等间距与多个顶部
【发布时间】:2018-01-31 07:33:30
【问题描述】:

我正在尝试在 ggplot2 图表中创建一个图例,其中包含多条线,每条线上都有一个参数和值。由于我将符号作为变量,因此需要使用expression 来完成。为了创建新行,我使用了多个atop 命令,但这会导致最后一行的间距不均匀。请看我下面的例子:

library(ggplot2)

N = 25

a = -5
b = 2
sigma = 1

x = runif(N, 0, 10)
y = a + x * b + rnorm(N, sd = sigma)

df = data.frame(x, y)

ggplot(df, aes(x, y)) +
  geom_point() +
  geom_label(aes(x = 1, y = max(y) - 2),
             label = paste0("atop(atop(",
                            "textstyle(a == ", a, "),",
                            "textstyle(b == ", b, ")),",
                            "textstyle(sigma == ", sigma, "))"
             ), parse = TRUE
  )
ggsave("plotmath_atop.png", width = 6, height = 4, scale = 1)

这给出了以下情节: 如您所见,b=2\sigma=1 行之间的间距明显大于a=-5b=2 行之间的间距。

有没有办法使用expression 与多个换行符同时仍然保持每行之间的间距均匀?

【问题讨论】:

标签: r ggplot2 plotmath


【解决方案1】:

你可以使用 gridExtra::tableGrob,

library(gridExtra)
library(grid)

table_label <- function(label, params=list())  {

  params <- modifyList(list(hjust=0, x=0), params)

  mytheme <- ttheme_minimal(padding=unit(c(1, 1), "mm"), 
                            core = list(fg_params = params), parse=TRUE)
  disect <- strsplit(label, "\\n")[[1]]
  m <- as.matrix(disect)
  tg <- tableGrob(m, theme=mytheme)
  bg <- roundrectGrob(width = sum(tg$widths) + unit(3, "mm"), height = sum(tg$heights) + unit(3, "mm"))
  grobTree(bg, tg)

}

txt <- 'a == -5\n
        b == 2\n
        sigma == 1'


library(ggplot2)

qplot(1:10,1:10) +
  annotation_custom(table_label(txt), xmin=0, xmax=5, ymin=7.5)

【讨论】:

    【解决方案2】:

    一个简单的解决方案是避免使用表达式,使用 unicode 字符 \u03c3 打印 sigma 字母,并使用 \n 进行换行。

    library(ggplot2)
    N = 25
    a = -5
    b = 2
    sigma = 1
    df = data.frame(runif(N, 0, 10), a + x * b + rnorm(N, sd = sigma))
    
    lab <- paste0("a = ", a, "\n",
                  "b = ", b, "\n",
                  "\u03c3 = ", sigma)
    
    ggplot(df, aes(x, y)) +
    geom_point() +
    geom_label(aes(x = 1, y = max(y) - 2), label =  lab, parse = FALSE)
    
    ggsave("plot_multiline_label.png", width = 6, height = 4, scale = 1)
    

    【讨论】:

    • 谢谢,但不幸的是,我不相信 unicode 能满足我的需求。虽然 sigma 符号与 expression 中的符号非常相似,但其他符号(例如 tau)与标准字体不匹配且不匹配。此外,我需要将一些变量名斜体化,这似乎不适用于此解决方案(如果我错了,请纠正我)。
    猜你喜欢
    • 2021-04-14
    • 2022-01-15
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多