Home > Net >  ggplot2 create custom theme with predefined labels
ggplot2 create custom theme with predefined labels

Time:01-28

I have a very simple questions but didnt find an answer online.. I am not even sure if this functionality exists in ggplot2.

For different types of plots, I usually create themes, so I dont have to type everything out each time I am regenerating a plot with different data.

The code might look something like this:


theme_UMAP <- function(x){
theme(...,
            legend.key = element_rect(colour = NA),
            legend.position = "bottom",
            legend.direction = "horizontal",
            legend.key.size= unit(0.8, "cm"),
            legend.spacing = unit(0, "cm"),
            legend.title = element_text(face="bold",size=15),
            legend.text = element_text(size=14),
            plot.margin=unit(c(2,1,1,1),"mm"),
            strip.background=element_rect(colour="#f0f0f0",fill="#f0f0f0"),
            strip.text = element_text(face="bold")}

Now for this particular theme, I know that the X-label will always be UMAP 1 and the Y-label will always be UMAP 2. I would love to include this in the function by doing something like this:

theme_UMAP <- function(x){
theme(...,
            legend.spacing = unit(0, "cm"),
            legend.title = element_text(face="bold",size=15),
            legend.text = element_text(size=14),
            plot.margin=unit(c(2,1,1,1),"mm"),
            strip.background=element_rect(colour="#f0f0f0",fill="#f0f0f0"),
            strip.text = element_text(face="bold") 
xlab("UMAP 1") 
ylab("UMAP 2")}

However, this results in the following error:

Error:
! Theme element `x` is not defined in the element hierarchy.

Any ideas how to achieve what I am trying to do is very much appreciated!

Cheers!

CodePudding user response:

First issue with your code is that you have put x/ylab inside theme. Second, if you want to put multiple layers in function then use a list:

Using a minimal example based on mtcars:

library(ggplot2)

theme_UMAP <- function(x) {
  list(
    theme(
      legend.spacing = unit(0, "cm"),
      legend.title = element_text(face = "bold", size = 15),
      legend.text = element_text(size = 14),
      plot.margin = unit(c(2, 1, 1, 1), "mm"),
      strip.background = element_rect(colour = "#f0f0f0", fill = "#f0f0f0"),
      strip.text = element_text(face = "bold")
    ),
    xlab("UMAP 1"),
    ylab("UMAP 2")
  )
}

ggplot(mtcars, aes(hp, mpg))  
  geom_point()  
  theme_UMAP()

  • Related