r - 用颜色向量突出显示 ggplot2 中的前 3 个

标签 r ggplot2

我有一个下面的代码,我想用选定的颜色为前 3 个着色。非常感谢。

    library(ggplot2)
library(dplyr)

df <- data.frame(dose = c("D0.5", "D1", "D2", "D3", "D4", "D5"),
                 len = c(4.2, 10, 29.5, 5, 7, 15))

df <- dplyr::mutate(df, top3 = rank(-len) %in% 1:3)


# Basic barplot
p <- ggplot(data = df, aes(x = reorder(dose, -len), y = len)) +
  geom_bar(stat = "identity", fill = ifelse(df$top3 == TRUE,  c("blue", "yellow", "green"), "grey50")) + 
           #color = ifelse(df$top3 == TRUE,  c("red", "yellow", "green"), "grey50")) +
  coord_flip()
p

最佳答案

你可以这样做:

df <- data.frame(dose = c("D0.5", "D1", "D2", "D3", "D4", "D5"),
                 len = c(4.2, 10, 29.5, 5, 7, 15))

df <- df |> 
  dplyr::arrange(desc(len)) |>
  dplyr::mutate(
    rank = factor(dplyr::row_number(), labels = dose)
  )

fill_colors = c("blue", "yellow", "green")
other_colors = rep("grey50", nrow(df)-length(fill_colors))
my_scale  <- c(fill_colors, other_colors)

withr::with_options(
  list(ggplot2.discrete.fill = my_scale),
  ggplot(data = df, aes(x = reorder(dose, -len), y = len)) +
  geom_bar(stat = "identity", aes(fill = rank)) +
  scale_fill_discrete() +
  coord_flip()
)

enter image description here

关于r - 用颜色向量突出显示 ggplot2 中的前 3 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72431049/

相关文章:

r:使用所有可能的选项和变量组合数量创建数据框

r - plotly -R : specifying size of marker in add_trace() reduces opacity of markers

r - 使用ggplot2用百分比绘制多个数据集的直方图

r - GGPLOT - 如何根据预定义标签区分线并在 x 轴上添加文本

r - 如何使用 ggplot 在 R 中多次更改线段的线型

r - 在ggplot中注释方程

R - ggplot2,几个问题,多个相关图

r - data.table 中的 ifelse 赋值

r - 如何在r中创建像数据(火山)这样的数据结构

r - ggplot geom_jitter 落后于(多个)geom_boxplot