[英]Manually change colour of one factor level in ggplot2 stacked barplot
考慮以下示例:
library(scales)
library(ggplot2)
ggplot(Arthritis)+
geom_bar(aes(x = Sex, group = Improved), fill = c("red", "blue", "green", "yellow", "grey50", "black"), position = "fill")
要更改指定的字段,而其他字段則保留默認的ggplot顏色:
ggplot(Arthritis)+
geom_bar(aes(x = Sex,
group = Improved),
fill = c(rev(hue_pal()(3)),
"black",
hue_pal()(3)[2:1]),
position = "fill")
或用陰影將其余的部分變灰
ggplot(Arthritis)+
geom_bar(aes(x = Sex,
group = Improved),
fill = c(paste0("grey", 7:9*10),
hue_pal()(3)[3],
paste0("grey", 8:9*10)),
position = "fill")
要保留圖例,只需在您的初始圖層上繪制以上內容即可:
ggplot(Arthritis)+
geom_bar(aes(x = Sex, fill = Improved), position = "fill")+
geom_bar(aes(x = Sex,
group = Improved),
fill = c(paste0("grey", 7:9*10),
hue_pal()(3)[3],
paste0("grey", 8:9*10)),
position = "fill")
另一個選擇是用NA替換我們要突出顯示的數據點,然后使用scale_fill_grey
為參數na.value
。 我們手動重新標記圖例以顯示原始名稱。
library(dplyr) ggplot(Arthritis %>% mutate(Improved = replace(Improved, Improved == "Marked", NA))) + geom_bar(position = "fill", aes(x = Sex, fill = Improved))+ scale_fill_grey(start = 0.8, end = 0.6, na.value = "RoyalBlue", labels = c("None", "Some", "Marked"))
ggplot(Arthritis %>% mutate(Improved = replace(Improved, Improved== "Marked" & Sex == "Male", NA))) + geom_bar(position = "fill", aes(x = Sex, fill = Improved))+ scale_fill_grey(start = 0.8, end = 0.2, na.value = "RoyalBlue", labels = c("None", "Some", "Marked", "Marked"))
您可以添加一個包含顏色映射的列,並將其與scales_fill_identity()
。
reprex::reprex_info()
#> Created by the reprex package v0.1.1.9000 on 2017-11-18
library(vcd)
#> Loading required package: grid
lvls <- levels(Arthritis$Improved)
color_maps <- scales::grey_pal(start = 0.8, end = 0.9)(length(lvls))
names(color_maps) <- lvls
library(dplyr, warn.conflicts = FALSE)
Arthritis_w_fill <- Arthritis %>%
mutate(
fill = if_else(
Sex == "Male" & Improved == "Marked",
"blue",
color_maps[Improved]
)
)
library(ggplot2)
ggplot(Arthritis_w_fill, aes(x = Sex, fill = fill)) +
geom_bar(position = "fill") +
scale_fill_identity(guide = "legend",
breaks = c(color_maps, "blue"),
labels = c(lvls, 'Sex == "Male" & Improved == "Marked"'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.