r - 如何在geom_bar ggplot2中为许多列着色相同的颜色
问题描述
我有以下数据:
> Dummydata
Sample r.K
1 E1 0.084150
2 E2 0.015170
3 E3 0.010662
4 E4 0.016123
5 EK1 0.010289
6 EK2 0.017484
7 EK3 0.014685
8 EK4 0.014272
9 EK5 0.012551
10 K1 0.010069
11 K2 0.010253
12 K3 0.010568
13 K4 0.011230
14 K5 0.010286
我用我的数据做了一个 geom_col 图:
plot_dummy_data <- Dummydata %>% ggplot(aes(x = Sample, y =r.K)) +
geom_col(fill = "#FAE0B1") + labs(y= "fitness cost", x = "sample")
我想将前 4 列着色为与特定主机对应的相同颜色,然后将接下来的 5 列着色为另一种颜色,然后将最后 5 列着色为第三种颜色。
我看过函数 scale_fill_manual() 但我不明白如何为一组列而不是全部选择特定颜色。
我一直在尝试一整天,并在这里找到了所有我能找到的东西,但我仍然没有弄清楚。我是 R 的初学者,所以我非常感谢任何帮助。
解决方案
实现所需结果的一种选择是
- 为列组添加一个标识符,例如在您的示例数据的下面的代码中,您可以使用它
gsub("\\d", "", Sample)
来从Sample
列中删除数字。 - 在填充美学上映射组标识符变量。
- 通过 设置您想要的颜色
scale_fill_manual
。
library(ggplot2)
library(dplyr)
Dummydata %>%
mutate(group = gsub("\\d", "", Sample)) %>%
ggplot(aes(x = Sample, y = r.K, fill = group)) +
geom_col() +
scale_fill_manual(values = c(E = "red", EK = "blue", K = "yellow")) +
labs(y = "fitness cost", x = "sample")
数据
Dummydata <- structure(list(Sample = c(
"E1", "E2", "E3", "E4", "EK1", "EK2",
"EK3", "EK4", "EK5", "K1", "K2", "K3", "K4", "K5"
), r.K = c(
0.08415,
0.01517, 0.010662, 0.016123, 0.010289, 0.017484, 0.014685, 0.014272,
0.012551, 0.010069, 0.010253, 0.010568, 0.01123, 0.010286
)), class = "data.frame", row.names = c(
"1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14"
))