I'm trying to simplify my plots in ggplot2
. Suppose I want to create a scatterplot from iris dataset:
ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
geom_point()
But suppose I don't like ggplot2
default theme and palette. Let's say I want to use theme_bw
and Dark2
palette:
ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
geom_point() +
theme_bw() +
scale_color_brewer(palette="Dark2")
And suppose I have lots of plots and I want all of them using theme_bw
and Dark2
palette. I know I can use theme_set(theme_bw())
to make all my plots have the black and white theme. Is there a similar function to make all my plots use Dark2
palette? In other words, how can I run a code like
ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
geom_point()
and have theme_bw
and Dark2
palette in all my plots?
The ggthemr package was developed by a friend of mine, Ciarán Tobin, who works with me at KillBiller and Edgetier. The package gives a quick and easy way to completely change the look and feel of your ggplot2 figures, as well as quickly create a theme based on your own, or your company's, colour palette.
A color can be specified either by name (e.g.: “red”) or by hexadecimal code (e.g. : “#FF1234”).
theme_bw: A theme with white background and black gridlines.
Navigate to Tools → Global options → Appearance and switch the theme in the Editor Theme option. By default, you will have the Textmate theme activated. There is a wide in-built variety of themes to choose, from light to dark themes.
One solution would be to write a custom wrapper:
ggcust <- function(...){
ggplot(...) +
theme_bw()
}
fill in all the theme
options you need, then use it like this:
ggcust(data = mtcars, aes(x = mpg, y = cyl)) +
geom_point()
You can also put layers into a list
:
gglayer_theme <- list(
theme_bw(),
scale_color_brewer(palette="Dark2")
)
And treat the list like a new layer (Note +
becomes ,
in this list notation):
ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
geom_point() +
gglayer_theme
The advantage to the custom wrapper approach is the ability to easily mix layers:
gglayer_labs <- list(
labs(
x = "x",
y = "y"
)
)
ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
geom_point() +
gglayer_theme +
gglayer_labs
Or combine them beforehand:
gglayer_all <- c(gglayer_theme, gglayer_labs)
ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
geom_point() +
gglayer_all
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With