当标题是ggplot2中的变量时,如何更改标题标题的字体大小?

时间:2012-11-27 17:36:11

标签: r ggplot2

我正在使用ggplot2生成散点图。我把标题变成了变量,如何更改字体大小?代码如下:

library("ggplot2")
plotfunc <- function(x){
    x +
    geom_point() +
    geom_smooth(se = FALSE, method = "lm",  color = "blue", size = 1) +
    opts(title = plottitle,
           axis.title.x = theme_text(size = 8, colour = 'black'),
         axis.title.y = theme_text(size = 8, colour = 'black', angle = 90))
}

plottitle <- "This is Title"
p <- ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width))
plotfunc(p)

我试过

opts(title = plottitle (size = 10),...

但是出现了错误:

Error in opts(title = plottitle(size = 10),
axis.title.x = theme_text(size = 8,  : could not find function "plottitle"

它被认为是不是我想要的功能。 我该怎么办?感谢。

3 个答案:

答案 0 :(得分:8)

如果 opts()仍适用于您,那么您使用的是旧版本的ggplot2。较新的命令是主题()。在任何情况下,您都不希望将实际标题标签放入 opts 主题 - 使用 labs()

plotfunc <- function(x) {
  x +
    geom_point() +
    geom_smooth(se = FALSE, method = "lm",  color = "blue", size = 1) +
    theme_bw() +
    theme(axis.title.x = element_text(size = 8, colour = 'black'),
          axis.title.y = element_text(size = 8, colour = 'black', angle = 90)) +
    labs(title='this', x='that', y='the other')
}

## plottitle <- "This is Title"
p <- ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width))
plotfunc(p)

enter image description here

答案 1 :(得分:6)

可笑的迟到答案,但我不认为现有的答案解决了实际问题:

  

我将标题变成了变量,如何更改字体大小?

这对我有用,并采用更新的ggplot语法(theme()opts()):

library(ggplot2)
plotfunc <- function(x){
    x +
    geom_point() +
    geom_smooth(se = FALSE, method = "lm",  color = "blue", size = 1) +
    labs(title = plottitle) +
    ### pay attention to the ordering of theme_bw() vs. theme()
    theme_bw() +
    theme(plot.title = element_text(size = 20),
          axis.title.x = element_text(size = 12),
          axis.title.y = element_text(size = 8))

}

plottitle <- "This is Title"
p <- ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width))
plotfunc(p)

我得到以下内容:

ggplot theme(plot.title)

关于我的theme_bw()评论的说明:尝试运行上述内容,但在theme_bw()位之后将theme(plot.title, ...)放在最后,如上面的Stephen Henderson的答案。您会注意到没有任何字体大小生效。这是因为theme_bw()是一个预设,如果您在添加后将其传递,则会覆盖各种自定义theme()选项。

只是一个值得注意的事情;我只是学习了它,因为我经常使用theme_bw()并试图弄清楚为什么其他theme()选项在我意识到它不是{{1}毕竟语法,但我的设置的顺序。喜欢编码:)。

另外,这里的the full list of options您可以传递给ggplot,作为您可以调整的内容和方式的参考。

答案 2 :(得分:1)

你在plottitle之后放了一个“(”作为下一个非空白字符,所以解释器决定它必须是一个函数。试试

  .... opts( title=plottile, size=10)

这是一长串的变暖信息:

Warning messages:
1: 'opts' is deprecated.
Use 'theme' instead.
See help("Deprecated") 
2: 'theme_text' is deprecated.
Use 'element_text' instead.
See help("Deprecated") 
3: 'theme_text' is deprecated.
Use 'element_text' instead.
See help("Deprecated") 
4: In opts(title = plottitle, axis.title.x = theme_text(size = 8, colour = "black"),  :
  Setting the plot title with opts(title="...") is deprecated. Use labs(title="...") or ggtitle("...") instead.