我有以下簡單的 MWE。
set.seed(2022102517)
df <- data.frame(letter =factor(colors()[1:8], levels = colors()[1:8]), value = rnorm(8))
library(ggplot2)
ggplot(data = df, aes(x = letter, y = value, group = 1)) geom_line()
這給了我每個“字母”的“價值”線圖,如下所示:

注意排序。
現在,我想做的是在每個不同(分配的)顏色(來自fill.col)(在x軸上)的顏色名稱前面有一個小方塊。所以,基本上,只要我們在 x 軸上有一個字母,然后在每個字母的左側添加一個填充顏色框,顏色就是從那里拾取的,比如說,fill.col。
fill.col <- c("#005A32", "#FC8D62", "#D95F02", "#8DA0CB", "#7570B3", "#E78AC3", "#E7298A", "#A6D854")
我嘗試了以下方法(來自下面提供的解決方案):
library(tidyverse)
library(RColorBrewer)
library(ggtext)
df %>%
mutate(new_letter = paste("<span style = 'color: ",
fill.col,
";'>",
"\u25a0",
"</span>",
" ",
letter,
sep = ""),
new_letter = fct_reorder(new_letter, as.character(letter))) %>%
ggplot(aes(new_letter, value, group = 1))
geom_line()
theme(axis.text.x = element_markdown(size = 12))
這給了我:

在我看來,在這種情況下,我們正在按字母表重新排序“字母”,盡管這里的顏色附件似乎是正確的。是否可以保留原始順序以便我可以控制顯示幕?感謝您的進一步幫助和澄清!
uj5u.com熱心網友回復:
一個解決方案使用ggtext,基于
一種稍微簡單的方法是在軸主題中添加顏色,但這也會給字母著色(并生成警告):
df %>%
mutate(letter = paste("\u25a0", letter)) %>%
ggplot(aes(letter, value, group = 1))
geom_line()
theme(axis.text.x = element_text(color = brewer.pal(8, "Set2")))
結果:

uj5u.com熱心網友回復:
這很麻煩,但我想不出更好的解決方案:
set.seed(2022102517)
df <- data.frame(letter =letters[1:8], value = rnorm(8))
library(ggplot2)
ggplot(data = df, aes(x = letter, y = value, group = 1))
geom_line()
coord_cartesian(clip = "off", ylim = c(-0.5, 1.2))
annotate("rect", fill = "#66C2A5",
xmin = 0.7, xmax = 0.85,
ymin = -0.65, ymax = -0.6)
annotate("rect", fill = "#FC8D62",
xmin = 1.7, xmax = 1.85,
ymin = -0.65, ymax = -0.6)
annotate("rect", fill = "#8DA0CB",
xmin = 2.7, xmax = 2.85,
ymin = -0.65, ymax = -0.6)
annotate("rect", fill = "#E78AC3",
xmin = 3.7, xmax = 3.85,
ymin = -0.65, ymax = -0.6)
annotate("rect", fill = "#A6D854",
xmin = 4.7, xmax = 4.85,
ymin = -0.65, ymax = -0.6)
annotate("rect", fill = "#FFD92F",
xmin = 5.7, xmax = 5.85,
ymin = -0.65, ymax = -0.6)
annotate("rect", fill = "#E5C494",
xmin = 6.7, xmax = 6.85,
ymin = -0.65, ymax = -0.6)
annotate("rect", fill = "#B3B3B3",
xmin = 6.7, xmax = 6.85,
ymin = -0.65, ymax = -0.6)
annotate("rect", fill = "grey50",
xmin = 7.7, xmax = 7.85,
ymin = -0.65, ymax = -0.6)

由reprex 包(v2.0.1)于 2022 年 10 月 27 日創建
這是否解決了您的問題,還是您正在尋找更“靈活”的解決方案?
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/520899.html
標籤:rggplot2
上一篇:遍歷資料框中的一行以更改型別別
下一篇:ggplot為條形圖填充顏色
