Home > Software engineering >  How to add a caption/subtitle to corrplot plot (R)
How to add a caption/subtitle to corrplot plot (R)

Time:09-15

I have produced a corrplot plot that gives correlation between variables. I now simply want to add a subtitle/caption to note things about the variables, at the bottom of the plot. However, because it's not like ggplot, I cannot seem to make the label appear. I have used the argument main = to produce a title, but sub = does not produce anything.

Is it possible to add a subtitle to a corrplot rendering? If not, is there a way to take the corrplot output and put it into another object that would allow me to add a caption/subtitle?

My plot looks like this:

enter image description here

And my code is this:

correlation_plot <- corrplot(corr = cortable, method = "number", main = "Title", sub = "sub", type = "full", number.cex=0.70)

where cortable is a generic dataframe of observations for columns A-E.

Also, is there a way to stop the Title from being cut off at the top? Is that cutoff whats actually preventing me from seeing a subtitle too?

CodePudding user response:

The problem is that corrplot changes the default margins and so cuts off both the title and subtitle.

library(corrplot)
corrplot(cor(iris[,1:4]), main = "title", sub="subtitle")

Cropped corrplot

You can do better, by specifying a margin more like the defaults

corrplot(cor(iris[,1:4]), main = "title", sub="subtitle", mar=c(5,4,4,2))

Bigger margins

But to get a really good result, specify a modest margin and then add the title and subtitle separately using title

corrplot(cor(iris[,1:4]), mar=c(1,1,2,1))
title(main="title", sub="subtitle")

Titles added separately

Experiment with the margin size to get a placement that looks good for your corrplot.

CodePudding user response:

If you want some flexibility and like ggplot2 you can plot the cor matrix using a little data transformation:

library(tidyverse)

#sample data
df <- tibble(var = rep(LETTERS[1:5], each = 10),
       val = runif(length(var))) |>
  group_by(var) |>
  mutate(id = row_number()) |>
  pivot_wider(names_from = var, values_from = val) |>
  select(-id)

cortable <- cor(df)

as.data.frame(cortable) |>
  rownames_to_column("yvar") |>
  pivot_longer(cols = A:E, names_to = "xvar") |>
  mutate(across(c(xvar, yvar), as.factor)) |>
  ggplot(aes(xvar, yvar))  
  geom_tile(fill = NA, color = "gray") 
  geom_text(aes(label = round(value, 2), color = value)) 
  scale_color_gradient2(low = "darkred", mid = "white", high = "darkblue") 
  scale_y_discrete(limits = rev) 
  theme(panel.background = element_blank(),
        panel.border = element_rect(fill = NA, color = "black")) 
  ggtitle("Title", subtitle = "sub")

  • Related