使用ggplot添加动态字幕 [英] Add dynamic subtitle using ggplot

查看:126
本文介绍了使用ggplot添加动态字幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ggplot添加字幕。这里提出了类似的问题:如何添加ggplot2不同大小和颜色的字幕?,答案如下:

  p < -  p + ggtitle(表达式(粘贴('TITLE'),顶部(斜体(粘贴('SUBTITLE')),))))

但是,'TITLE'和'SUBTITLE'硬编码,在处理1000个地块时呈现可伸缩性和自动化问题。



这不起作用:

 plot.title ='TITLE'
plot.subtitle ='SUBTITLE'
p < - p + ggtitle(expression(atop(paste(plot.title),atop (斜体(paste(plot.subtitle)),))))

关于如何正确添加动态字幕,使用这个想法,归结为:是否有可能在expr中使用字符变量你应该使用函数 bquote()而不是 expression()使用存储为变量的标题。变量名应放在。()

中。

  plot.title ='TITLE'
plot.subtitle ='SUBTITLE'

ggplot(mtcars,aes(disp,mpg))+ geom_point()+
ggtitle(bquote(atop(。 (plot.title),atop(italic(。(plot.subtitle)),))))


更新 - ggplot2版本2.2.1 b
$ b

最新的ggplot2版本现在可以直接产生字幕,所以你不必使用 bquote() expression()。结果以函数 labs()的参数 subtitle = 来实现。

  ggplot(mtcars,aes(disp,mpg))+ geom_point()+ 
labs(title = plot.title,subtitle = plot.subtitle)+
主题(plot.subtitle = element_text(face =italic))


I am trying to use ggplot to add a subtitle. Similar question was asked here: How to add a ggplot2 subtitle with different size and colour?, and the answer was as follows:

p <- p + ggtitle(expression(atop(paste('TITLE'), atop(italic(paste('SUBTITLE')), ""))))

However, the words 'TITLE' and 'SUBTITLE' need to be hardcoded, presenting an scalability and automation problem when dealing with 1000s of plots.

This does not work:

plot.title = 'TITLE'
plot.subtitle = 'SUBTITLE'    
p <- p + ggtitle(expression(atop(paste(plot.title), atop(italic(paste(plot.subtitle)), ""))))

I guess the question on how to proper add dynamic subtitles, using this idea, boils down to: Is it possible to use character variables inside expression and atop?

解决方案

You should use function bquote() instead of expression() to use titles that are stored as variables. And variable names should be placed inside .()

plot.title = 'TITLE'
plot.subtitle = 'SUBTITLE'

ggplot(mtcars,aes(disp,mpg))+geom_point()+
  ggtitle(bquote(atop(.(plot.title), atop(italic(.(plot.subtitle)), "")))) 

UPDATE - ggplot2 version 2.2.1

The latest ggplot2 version now can produce subtitles directly, so you don't have to use bquote() and expression(). The result is atchieved with argument subtitle = of function labs().

ggplot(mtcars,aes(disp,mpg))+geom_point()+
      labs(title = plot.title,subtitle = plot.subtitle) +
      theme(plot.subtitle = element_text(face = "italic"))

这篇关于使用ggplot添加动态字幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆