How do I create a custom theme similar to theme_bw in ggplot2?
I have the following codes in ggplot2:
require("ggplot2")
df <- data.frame(x=factor(rep(1:2,5)), y=rnorm(10))
ggplot(df , aes(x,y)) + geom_point(size = 3) +
theme(axis.text.x = element_text(angle = 40, hjust = 1, colour = "black", size=12),
plot.title = element_text(size=16, face="bold", hjust=0.5)) +
labs(title = "Plot")
Now I want to change the background color to theme_bw, but then the main title and x-axis parameters will be changed to the default.
ggplot(df , aes(x,y)) + geom_point(size = 3) +
theme(axis.text.x = element_text(angle = 40, hjust = 1, colour = "black", size=12),
plot.title = element_text(size=16, face="bold", hjust=0.5)) +
labs(title = "Plot") +
theme_bw()
So how can I change the theme in the same way as theme_bw, but without losing other parameters?
thank
source to share
Here's the solution (make sure to theme_bw()
use before theme()
which you want to apply:
ggplot(df , aes(x,y)) + geom_point(size = 3) +
theme_bw() +
theme(axis.text.x = element_text(angle = 40, hjust = 1, colour = "black", size=12),
plot.title = element_text(size=16, face="bold", hjust=0.5)) +
labs(title = "Plot")
source to share
Another interesting option is to write a function that only updates the theme if the theme elements are not yet defined. This way it will look like +
but themes cannot be overwritten, only added:
`%+safe%` <- function(e1, e2){
if (!is.theme(e1) || !is.theme(e2)) {
stop("%+replace% requires two theme objects", call. = FALSE)
}
not_in_e1 <- names(e2)[!names(e2) %in% names(e1)]
e1[not_in_e1] <- e2[not_in_e1]
e1
}
ggplot(df , aes(x,y)) + geom_point(size = 3) + labs(title = "Plot") +
theme(axis.text.x = element_text(angle = 40, hjust = 1, colour = "black", size=12),
plot.title = element_text(size=16, face="bold", hjust=0.5)) %+safe% theme_bw()
Please note that for this you need to take two objects theme
so that you move anyway labs()
.
source to share