我在下面有一個代碼,我想用選定的顏色為前 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
uj5u.com熱心網友回復:
你可以這樣做:
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(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()
)

uj5u.com熱心網友回復:
您可以在資料框中添加一個額外的顏色等級列,并相應地更改顏色scale_fill_manual:
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))
df <- dplyr::mutate(df, col_rank = as.character( ifelse(top3 > 3, 4, top3)))
# Basic barplot
p <- ggplot(data = df, aes(x = reorder(dose, -len), y = len, fill = col_rank))
geom_bar(stat = "identity")
coord_flip()
scale_fill_manual(values = c("1" = "blue", "2" = "yellow", "3" = "green", "4" = "grey50"))
p
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/482642.html
上一篇:使用AWSStepFunctions更新DynamoDB中的專案時,為什么會收到“需要專案”?
下一篇:如何在列行中添加新字串
