r - ggplot斜体标题的一部分,并将文本分成两行

标签 r ggplot2 paste

我想在图表中添加以下标题:

Note: Market concentration averages in the United States, United Kingdom, and the Netherlands are, respectively, 1920, 1388, and 1244



“注:”需要用斜体表示,“荷兰分别是1920、1388和1244”应该放在新的一行。

使用paste函数,我可以将其倾斜。但是,使用\n中的paste,将所有内容混合在一起,就像您在此处看到的一样(这是经过编辑的图像,是使用下面的Paul的建议制作的):

enter image description here

我尝试了其他各种解决方案,但没有成功。这是我正在使用的代码:
library(ggplot2)

note = expression(paste(italic("Note: "), "Market concentration averages in the United States, United Kingdom, and the \nNetherlands are, respectively, 1920, 1388, and 1244"))

gg <- ggplot(mtcars, aes(wt, mpg)) + geom_point()+

# Title
labs(caption=note)

gg + theme(plot.caption=element_text(size=7.5, hjust=0, margin=margin(t=15)))

最佳答案

基于this answer

library(grid)
library(ggplot2)


ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_line() + 
  labs(caption= "First~line \n italic('and a second,')~bold('fancy one') \n
       'also,'~integral(f(x)*dx, a, b)~'for good measure'")+
  (theme_grey() %+replace% theme(plot.caption = element_custom()))

enter image description here
element_custom <- function() {
  structure(list(), class = c("element_custom", "element_text"))
}

element_grob.element_custom <- function(element, label="", ...)  {
  disect <- strsplit(label, "\\n")[[1]]
  labels <- lapply(disect, function(x) tryCatch(parse(text=x), 
                                                error = function(e) x))
  hl <-  unit(rep(1, length(labels)), 'strheight', data=labels) + unit(0.1,"line")
  yl <- c(list(unit(0,"line")), 
          lapply(seq_along(labels[-length(labels)]), function(ii) sum(hl[1:ii])))

  cl <- do.call(gList, Map(function(label, ii) 
    textGrob(label, y = unit(1,"npc")-yl[[ii]], hjust=0, x=0, vjust=1), 
    label = labels, ii = seq_along(labels)))

  gTree(children = cl, cl="sl", heights = hl, gp=gpar(col="grey50",fontsize=8))
}

heightDetails.sl <- function(x) sum(x$heights)

关于r - ggplot斜体标题的一部分,并将文本分成两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47186918/

相关文章:

r - 使用 ggplot2 可视化从 MClust 中提取的簇

R geom_bar facet_grid 垂直而不是水平

html - 如何使用 Dart 将剪贴板中的图像粘贴到 Canvas 元素上?

r - 如何在sf R包中按组测量空间点之间的距离

r - 根据值和分隔符拆分数据框中的所有列

r - 来自 data.table::frollmean() 的意外高内存使用

R 如何在不知道长度的情况下创建 for 循环?

r - ggplot2 使用开环或闭环

python - 在 web.py 应用程序上使用粘贴测试 400 错误

JavaScript 粘贴事件在 Chrome 中运行良好,但在 Firefox 中运行不正常