ggplot斜体标题的一部分,并将文本分成两行 [英] ggplot italicize part of caption AND divide text over two lines
问题描述
我想在图形中添加以下标题:
I like to add the following caption to my graph:
注:美国,美国的市场集中度平均值 王国和荷兰分别是1920、1388和1244
Note: Market concentration averages in the United States, United Kingdom, and the Netherlands are, respectively, 1920, 1388, and 1244
注:"需要用斜体显示,荷兰分别是1920、1388和1244"应该放在新的一行.
Where 'Note:' needs to be italicized, and 'Netherlands are, respectively, 1920, 1388, and 1244' should be placed on a new line.
使用paste
功能,我可以将其倾斜.但是,使用paste
中的\n
混合所有内容(如您在此处看到的那样(这是经过编辑的图像,是根据下面Paul的建议制作的):
Using the paste
function, I can italize a part. But using the \n
within paste
, mixes every thing up as you can see here (this is an edited image, made using Paul's advice below):
我尝试了其他各种解决方案,但是没有成功.这是我正在使用的代码:
I tried various other solutions, but without succes. Here is the code I am using:
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)))
推荐答案
基于此答案,
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)
这篇关于ggplot斜体标题的一部分,并将文本分成两行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!