我正在使用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)
Run Code Online (Sandbox Code Playgroud)
我试过了
opts(title = plottitle (size = 10),...
Run Code Online (Sandbox Code Playgroud)
但是有一个错误:
Error in opts(title = plottitle(size = 10),
axis.title.x = theme_text(size = 8, : could not find function "plottitle"
Run Code Online (Sandbox Code Playgroud)
它被认为是不是我想要的功能.我该怎么办?谢谢.
如果opts()仍然适用于您,那么您使用的是旧版本的ggplot2.较新的命令是theme().在任何情况下,您都不希望将实际标题标签放入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)
Run Code Online (Sandbox Code Playgroud)

可笑的迟到答案,但我不认为现有的答案解决了实际问题:
我把标题变成了变量,如何更改字体大小?
这对我有用,并且在更新的ggplot语法中(theme()vs. 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)
Run Code Online (Sandbox Code Playgroud)
我得到以下内容:

关于我的theme_bw()评论的一个注释:尝试运行上面的内容,但是在theme_bw()最后theme(plot.title, ...)一点之后,就像上面的Stephen Henderson的回答一样.您会注意到没有任何字体大小生效.这是因为如果在添加后将其传递theme_bw(),则会覆盖各种自定义theme()选项的预设.
只是一个值得注意的东西; 我只是学会了它,因为theme_bw()我使用了很多东西,并试着弄清楚为什么其他theme()选项不起作用,然后才意识到它不是我的ggplot语法,而是我的设置顺序.得爱编码:)
此外,这里是您可以传递的完整选项列表,theme()作为您可以调整的内容和方法的参考.
您将“(”作为下一个非空白字符,plottitle因此解释器认为它必须是一个函数。尝试
.... opts( title=plottile, size=10)
Run Code Online (Sandbox Code Playgroud)
这是一长串温暖的信息:
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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11379 次 |
| 最近记录: |