我下面有一个代码,我想用所选的 colored颜色 给前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相关问答推荐

以R为基数排列奇数个图

变量计算按R中的行更改

为什么st_join(ob1,ob2,left = True)返回具有比ob1更多功能的sf对象?

使用tidyverse / Mutate的存款账户余额

从R导出全局环境中的所有sf(numrames)对象

ggplot的轴标签保存在officer中时被剪切

如何在ggplot中标记qqplot上的点?

使用整齐的计算(curl -curl )和杂音

使用R闪光显示所有数据点作为默认设置

在使用bslb和bootstrap5时,有没有办法更改特定dt行的 colored颜色 ?

Ggplot2中geom_tile的动态zoom

如何在PDF格式的kableExtra表格中显示管道字符?

正则表达式在第二个管道和第二个T之后拆分R中的列

R中Gamma回归模型均方误差的两种计算方法不一致

如何使用字符串从重复的模式中提取多个数字?

如何筛选截止年份之前最后一个测量年度的所有观测值以及截止年份之后所有年份的所有观测值

通过R:文件名未正确写入[已解决]将.nc文件转换和导出为.tif文件

用满足特定列匹配的另一行替换NA行

排序R矩阵的行和列

在shiny 表格中输入的文本在第一次后未更新