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

ggplot italicize part of caption AND divide text over two lines

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

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

其中'Note:'需要斜体,'Netherlands are, respectively, 1920, 1388, and 1244'另起一行

使用 paste 函数,我可以将一部分斜体化。但是在 paste 中使用 \n,将所有内容混合在一起,正如您在此处看到的那样(这是一张经过编辑的图片,根据下面 Paul 的建议制作):

我尝试了各种其他解决方案,但都没有成功。这是我使用的代码:

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

这是否给了你想要的东西?

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

(不同的是"Note"部分现在也包含换行)

这是一种不同的方法:只需在 ggplot2 绘图中创建空 space(通过添加空白标题),然后导航到 ggplot2 为标题创建的视口,并将标题绘制为单独的文本行.

library(grid)

ggplot(mtcars, aes(wt, mpg)) + geom_point() + 
       labs(caption=expression(atop(" ", " ")))

grid.force()
downViewport("caption.9-4-9-4")
## grid.rect()
grid.text(expression(paste(italic("Note: "), 
                           "Market concentration averages in the United States, United Kingdom, and the")),
          x=0, y=unit(1, "npc") - unit(1, "line"), just=c("left", "top"),
          gp=gpar(fontsize=7.5))
grid.text("Netherlands are, respectively, 1920, 1388, and 1244",
          x=0, y=unit(1, "npc") - unit(2, "line"), just=c("left", "top"),
          gp=gpar(fontsize=7.5))

希望对您有所帮助

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

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)