gpt4 book ai didi

r - 标题中单个单词的颜色与组的颜色相匹配

转载 作者:行者123 更新时间:2023-12-02 00:49:30 25 4
gpt4 key购买 nike

我最近在《经济学人》中看到了一张折线图,其中 title had colored words to match the colors of the groups used in the line chart 。我想知道如何使用 ggplot2 对象来做到这一点。下面是一些代码,用于制作折线图,其中包含与经济学家文章类似的所有内容,但标题中的彩色单词除外。在底部我显示了所需的输出。

这个问题不是关于显示此信息的理论方法(例如直接标记或图例),而是关于为标题中的单个单词着色。

data <- data.frame(
group = rep(c('affluence', 'poverty'), each = 6),
year = rep(c(1970, 1980, 1990, 2000, 2010, 2012), 2),
concentration = c(.125, .12, .14, .13, .145, .146, .068, .09, .125, .119, .13, .135)
)

library(ggplot2)

ggplot(data, aes(year, concentration, color = group)) +
geom_line(size = 1.5) +
geom_point(size = 4) +
scale_y_continuous(limits = c(0, .15)) +
labs(
x = NULL, y = NULL,
title = 'Concentration of affluence and poverty nationwide'
) +
theme_minimal() +
theme(
legend.position = 'none'
) +
scale_color_manual(values = c('#EEB422', '#238E68'))

enter image description here

最佳答案

这是使用ggtext包的简单且更通用的方法

enter image description here

制作:

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

关于r - 标题中单个单词的颜色与组的颜色相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49735290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com