27

Is it possible to colorize parts of the title in a plot?

x = 1:10
y = 1:10
plot(x, y, main="title (slope=1)")

In this plot I'd like to change the color of slope=1 to red.

Tung
  • 26,371
  • 7
  • 91
  • 115
R_User
  • 10,682
  • 25
  • 79
  • 120

3 Answers3

36

This is a quite simple solution to your problem:

plot(x, y)
title(expression("title (" * phantom("slope=1)") * ")"), col.main = "black")
title(expression(phantom("title (") * "slope=1"), col.main = "red")

enter image description here

Alpha
  • 807
  • 1
  • 10
  • 14
  • Is it also possible to have part of a formula/mathematical expression in a different color? I want to have the part with the xs in a different color in this example: `plot(c(0, 10), c(0, 10), type = "n", axes = FALSE, xlab = "", ylab = ""); text(5, 6.6, expression(s^2 == frac(1, n-1) ~ ~ sum((x[i]-bar(x))^2, i==1, n))); text(5, 3.3, expression(s^2 == frac(1, n-1) ~ ~ sum((phantom(x[i]-bar(x)))^2, i==1, n)))` – MrMax Sep 20 '17 at 15:04
  • Nice hack :-) but I wouldn't call this "quite simple" as it is based on overlapping a "black" text and a "red" one, carefully `phantom`-ing out complementary parts. – András Aszódi Mar 17 '23 at 11:45
6

A solution for ggplot2 plots using the ggtext package

library(ggplot2)
# devtools::install_github("clauswilke/ggtext")
library(ggtext)

p <- ggplot(mtcars, aes(mpg, wt, colour = cyl)) + 
  geom_point(size = 3)

p + 
  labs(title = "New plot <b style='color:#009E73'>title</b>", 
       subtitle = "A <b style='color:#D55E00'>subtitle</b>") +
  theme_classic(base_size = 24) +
  theme(plot.title = element_markdown(lineheight = 1.1),
        plot.subtitle = element_markdown(lineheight = 1.1))

Created on 2019-08-11 by the reprex package (v0.3.0)

Tung
  • 26,371
  • 7
  • 91
  • 115
1

The ggtext package can do this

enter image description here

library(ggtext) #remotes::install_github("wilkelab/ggtext")

ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
  geom_point(size = 3) +
  scale_color_manual(
    name = NULL,
    values = c(setosa = "#0072B2", virginica = "#009E73", versicolor = "#D55E00"),
    labels = c(
      setosa = "<i style='color:#0072B2'>I. setosa</i>",
      virginica = "<i style='color:#009E73'>I. virginica</i>",
      versicolor = "<i style='color:#D55E00'>I. versicolor</i>")
  ) +
  labs(
    title = "**Fisher's *Iris* dataset**  
    <span style='font-size:11pt'>Sepal width vs. sepal length for 
    <span style='color:#0072B2;'>setosa</span>, 
    <span style='color:#D55E00;'>versicolor</span>, and
    <span style='color:#009E73;'>virginica</span>
    </span>",
    x = "Sepal length (cm)", y = "Sepal width (cm)"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_markdown(lineheight = 1.1),
    legend.text = element_markdown(size = 11)
  )
stevec
  • 41,291
  • 27
  • 223
  • 311