使用 ggplot 突出显示条形图中的三个特定条形

问题描述 投票:0回答:1

我正在尝试使用

ggplot
突出显示条形图中的特定条形。我的最终目标是以不同颜色突出显示三个条形,例如
blue
red
orange 
,我想保留其余的条形
lightgreen

到目前为止,这是我的代码:

`
#Barplot
Population <-ggplot(data= na.omit(RV), aes(x= reorder(Genotype, Rate), y= Rate)) +

  geom_col(aes(fill = Genotype != "RAPxSPL 410-1")) + 
  scale_fill_manual(values = c("blue", "lightgreen" ), guide = "none") +
    labs(title = "RAPxSPL 410-1 x Line V - Ratio VIP/MOCK", x = "Genotype", y = "Ratio VIP/MOCK")

Population + coord_flip()`

我知道我必须创建新的填充级别=,但每次我尝试时,我都会将所有条形变为灰色

enter image description here

r ggplot2 graph
1个回答
0
投票

技巧是创建一个填充颜色的命名向量,每个基因型有一个向量元素。这是通过

setNames
完成的。在准备过程中,首先将基因型列与要突出显示的基因型相匹配。然后去掉
NA
。这已经创建了
fill
颜色向量的索引。然后设置名称,使用索引
i
复制填充颜色。

测试数据集是仅包含相关列的示例数据集。

library(ggplot2)

set.seed(2024)
RV <- data.frame(
  Genotype = LETTERS[1:20],
  Rate = runif(20)
)
# the bars to highlight
hi <- sample(RV$Genotype, 3L)

i <- match(RV$Genotype, hi) + 1L
i[is.na(i)] <- 1L
fill <- c("lightgreen", "blue", "red", "orange")
fill <- setNames(fill[i], RV$genotype)

ggplot(RV, aes(reorder(Genotype, Rate), Rate, fill = Genotype)) +
  geom_col(show.legend = FALSE) +
  scale_fill_manual(values = fill) +
  labs(title = "RAPxSPL 410-1 x Line V - Ratio VIP/MOCK", x = "Genotype", y = "Ratio VIP/MOCK") +
  coord_flip() +
  theme_bw()

创建于 2024-09-24,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.