I am using ggplot2 to generate a scatter plot. I made the title into a variable, how can I change the font size? The code is as the following:
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)
I tried
opts(title = plottitle (size = 10),...
but there was an error:
Error in opts(title = plottitle(size = 10),
axis.title.x = theme_text(size = 8, : could not find function "plottitle"
It was recognized as function which was not what I want. What should I do? Thanks.
Ridiculously late answer, but I didn't think the existing answers addressed the actual question:
This works for me and is in the updated
ggplot
syntax (theme()
vs.opts()
):I get the following:
A note about my
theme_bw()
comment: try running the above, but puttheme_bw()
last, after thetheme(plot.title, ...)
bit, as in Stephen Henderson's answer above. You'll note that none of the font sizes take effect. This is becausetheme_bw()
is a preset which will overwrite various customtheme()
options if you pass it after they are added.Just a finnicky thing to watch out for; I've only learned it due to using
theme_bw()
a lot and banging my head against the wall trying to figure out why othertheme()
options weren't working before realizing it wasn't myggplot
syntax after all, but the order of my settings. Gotta love coding :)Also, here's the full list of options you can pass to
theme()
as a reference for what you can tweak and how.If opts() still works for you then you are using an old version of ggplot2. The newer command is theme(). In any case you don't want to put the actual title label into opts or theme -- use labs()
You put a "(" as the next non-whitespace character after
plottitle
so the interpreter decided it must be a function. TryThis was the long list of warming messages: