Call theme_light()
first to not overwrite theme(plot.title = element_text(hjust = 0.5))
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
ggtitle("Flowers") +
theme_light() +
theme(plot.title = element_text(hjust = 0.5))
If you look at the code of theme_light()
you'll see it calls theme_grey()
and theme()
.
function (base_size = 11, base_family = "", base_line_size = base_size/22,
base_rect_size = base_size/22)
{
half_line <- base_size/2
theme_grey(base_size = base_size, base_family = base_family,
base_line_size = base_line_size, base_rect_size = base_rect_size) %+replace%
theme(panel.background = element_rect(fill = "white",
colour = NA), panel.border = element_rect(fill = NA,
colour = "grey70", size = rel(1)), panel.grid = element_line(colour = "grey87"),
panel.grid.major = element_line(size = rel(0.5)),
panel.grid.minor = element_line(size = rel(0.25)),
axis.ticks = element_line(colour = "grey70", size = rel(0.5)),
legend.key = element_rect(fill = "white", colour = NA),
strip.background = element_rect(fill = "grey70",
colour = NA), strip.text = element_text(colour = "white",
size = rel(0.8), margin = margin(0.8 * half_line,
0.8 * half_line, 0.8 * half_line, 0.8 * half_line)),
complete = TRUE)
}
Now somewhere in theme_grey()
you'll find the following line:
plot.title = element_text(size = rel(1.2), hjust = 0
So when call theme(plot.title = element_text(hjust = 0.5))
first it will be overwritten by theme_light()
.
In cases where you'll find yourself repeatedly typing something like
ggplot() +
geom_something() +
theme(plot.title = element_text(hjust = 0.5)) +
theme_light()
you might define your own theme to save some typing
theme_WoeIs <-
function(base_size = 11,
base_family = "",
base_line_size = base_size / 22,
base_rect_size = base_size / 22,
...) {
half_line <- base_size / 2
theme_grey(
base_size = base_size,
base_family = base_family,
base_line_size = base_line_size,
base_rect_size = base_rect_size
) %+replace%
theme(
panel.background = element_rect(fill = "white",
colour = NA),
panel.border = element_rect(
fill = NA,
colour = "grey70",
size = rel(1)
),
panel.grid = element_line(colour = "grey87"),
panel.grid.major = element_line(size = rel(0.5)),
panel.grid.minor = element_line(size = rel(0.25)),
axis.ticks = element_line(colour = "grey70", size = rel(0.5)),
legend.key = element_rect(fill = "white", colour = NA),
strip.background = element_rect(fill = "grey70",
colour = NA),
strip.text = element_text(
colour = "white",
size = rel(0.8),
margin = margin(0.8 * half_line,
0.8 * half_line, 0.8 * half_line, 0.8 * half_line)
),
complete = TRUE,
plot.title = element_text(hjust = 0.5), # here is your part
... # this is new as well
)
}
Let's give it a try
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
ggtitle("Flowers") +
theme_WoeIs()