Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding CSS styling in the legend title in ggplot

I have below ggplot

library(ggplot2)
library(stringr)
library(tidyverse)

# Create long labels to be wrapped
iris$Species = paste(iris$Species, 
                     "random text to make the labels much much longer than the original labels")

ggplot(iris, aes(Sepal.Length, Sepal.Width, colour=str_wrap(Species,20))) +
  geom_point() +
  labs(colour="Long title shortened\nwith wrapping") +
  theme(legend.key.height=unit(2, "cm"))

I am wondering if I can apply some CSS styling in the legend title. For example, I want to change font size of the word wrapping to 12, whereas remaining words with font size 10.

Any pointer will be very helpful.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the package ggtext and the element_markdown for your legend.title with some CSS styling. You can modify to whatever you want. You can use the following code:

library(ggplot2)
library(stringr)
library(tidyverse)
library(ggtext)

# Create long labels to be wrapped
iris$Species = paste(iris$Species, 
                     "random text to make the labels much much longer than the original labels")

ggplot(iris, aes(Sepal.Length, Sepal.Width, colour=str_wrap(Species,20))) +
  geom_point() +
  labs(colour="<span style='font-size:10pt'>Long title shortened with </span><span style='font-size:12pt'>wrapped</span>") +
  theme(
    legend.title = element_markdown()
  )

Output:

enter image description here

As you can see the word wrapped has a font size of 12 and the other words have 10

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading