R ggplot annotated with atop using three values and bgroup

允我心安 提交于 2019-12-13 13:17:02

问题


Is there any way to annotate a ggplot with three lines one on top of the other, while keeping the text sizes the same across the three lines?

I am almost there but the text sizes are different in the third line, it looks like the bgroup is only using the first two lines and I cannot get this right...

I am adding the text using to "atop" applications from "?plotmath", which works fine but the text in the third line comes out in a different size compared to the other two lines...

library(ggplot2)
line1 = "xxx data1"
line2 = "yyy data2"
line3 = "zzz data3"

df=data.frame(x=rep(1:8, 3), y=c(0,1,3,4,5,6,7,8, 8,7,6,3,2,1,3,4, 0,2,4,5,6,7,8,9), variable=c("x", "x","x","x","x","x","x","x","y","y","y","y","y","y","y","y","z","z","z","z","z","z","z","z"))
p <-  ggplot(df) + theme_bw() + geom_point(aes(x=x,y=y, color=variable)) + geom_line(aes(x=x,y=y, color=variable)) + 
geom_text(x=max(df$x), y = max(df$y), label = paste('bgroup("{", atop(atop("',line1,'","',line2,'"),"', line3,'"), "}")',sep=''), size=3.5,parse=TRUE)

I thought I was getting all the three lines within the bgroup, but I cannot get the paste right. If there is anything I can try please advise. Thanks very much!


回答1:


To perfectly center everything (which \n will not do), keep every piece of text the same size whatever the number of lines and at the same time being able to adjust the interlinear space, use this instead:

xlab(expression(atop(textstyle("whateverline1"),atop(textstyle("whateverline2"),atop(scriptscriptstyle(""),textstyle("whateverline3"))))))

Then use labeller=label_parsed

This also works for facet_grid, title and ylab

Note the atop and textstyle to position the text whilst keeping it all the same size and the scriptscriptstyle("") to control spacing between lines. You can also use varied relative sizes of text using scriptstyle or scriptscriptstyle depending on your needs and of course use element_text(size=whatevernumber) in the theme section



来源:https://stackoverflow.com/questions/40577023/r-ggplot-annotated-with-atop-using-three-values-and-bgroup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!