Search code examples
rlegendcaption

How to place legend inside caption area on R


I am using R studio / R Markdown to create plots, some with ggplot, some with base R function. I would like to insert a caption for each of my plots which contains the legend similar to the example shown here:

Can anyone suggest how to place the legend of my plots (built with ggplot and base R functions) within the caption as shown in this example?

I searched online and found out that it is possible to use something like:

p +  labs(caption="Figure S1: This is the Figure Legend") 

however, I could not find how to embed the legend into the caption, and I also could not find a solution for plots made using base R.

There are some solutions that require Latex, but I cannot use Latex for this project.


Solution

  • You could just push the legend to the bottom and add a custom title - inlcude a counter to get numbered Plots:

    library(ggplot2)
    # using the internal iris dataset
    iris
    # set counter to zero
    NR <- 0
    
    # Add counter and build plot
    NR <- NR + 1
    legend <- paste0("Fig. ", NR, ": This is a Plot about...:")
    ggplot2::ggplot(iris, aes(Sepal.Length, Petal.Width, color = Species)) +
      ggplot2::geom_point() +
      ggplot2::labs(color= legend) +
      ggplot2::theme(legend.position = "bottom")
    
    
    # Add counter and build second plot
    NR <- NR + 1
    legend <- paste0("Fig. ", NR , ": This is a Plot about...:")
    ggplot2::ggplot(iris, aes(Sepal.Width, Petal.Length, color = Species)) +
      ggplot2::geom_point() +
      ggplot2::labs(color= legend) +
      ggplot2::theme(legend.position = "bottom")