【问题标题】:Colorize parts of the title in a plot为绘图中的标题部分着色
【发布时间】:2013-06-09 14:52:34
【问题描述】:

是否可以对绘图中的部分标题进行着色?

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

在这个情节中,我想将slope=1 的颜色更改为红色。

【问题讨论】:

  • 你可以通过两次调用 mtext 来做到这一点,但其他人可能有更好的方法。

标签: r ggplot2 plot colors formatting


【解决方案1】:

ggtext package 可以做到这一点

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)
  )

【讨论】:

  • 由于不再需要图例,您可以在主题中添加legend.position = "none"
【解决方案2】:

使用ggtext 包的ggplot2 绘图解决方案

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))

reprex package (v0.3.0) 于 2019 年 8 月 11 日创建

【讨论】:

    【解决方案3】:

    这是解决您的问题的一个非常简单的方法:

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

    【讨论】:

    • 公式/数学表达式的一部分是否也可以使用不同的颜色?在这个例子中,我想用不同颜色的 xs 部分: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)))
    猜你喜欢
    • 2021-10-18
    • 2019-09-21
    • 2013-10-22
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2016-11-24
    • 1970-01-01
    相关资源
    最近更新 更多