gpt4 book ai didi

r - 将额外的图例项添加到 ggplot2 以进行重叠填充 (geom_rect)

转载 作者:行者123 更新时间:2023-12-05 03:16:17 30 4
gpt4 key购买 nike

我想为两个 geom_rect 的重叠部分/颜色向 ggplot2 图例添加一个附加项。

代表:

# library
library(ggplot2)
library(tidyverse)

# make colors
adjustcolor("red", alpha.f = 0.1) -> red.tra
adjustcolor("blue", alpha.f = 0.1) -> blue.tra

#get data

data <- structure(list(unclear = c(0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0,
1), start = structure(c(12784, 13879, 9496, 17897, 11323, 12053,
16801, 16071, 17167, 17532, 16071, 11323, 11688), class = "Date"),
stop = structure(c(18628, 18628, 16801, 18262, 13879, 17897,
18262, 17897, 17532, 18628, 17897, 18262, 11688), class = "Date"),
group = c("R", "C", "C", "A", "A", "R", "M", "N",
"N", "O", "OB", "H", "H")), class = "data.frame", row.names = c(NA,
-13L))


#plot
ggplot(data = data)+
geom_rect(data = data %>% filter(unclear==0), aes(xmin=start, xmax=stop, ymin=0, ymax=0.7, fill="one")) +
geom_rect(data = data %>% filter(unclear==1), aes(xmin=start, xmax=stop, ymin=0, ymax=0.7, fill="two"))+
scale_fill_manual("colors",values=c(red.tra,blue.tra), labels=c("one","two"))+
facet_wrap(~group, ncol = 1, strip.position = "left")

创建于 2022-12-08 reprex v2.0.2

我正在寻找一种方法,使用透明蓝色和红色之间重叠的颜色将第三项添加到颜色图例中。

最佳答案

我使用 colorRampPalettered.trablue.tra 组合在一起,将它们放在渐变调色板中,然后选择介于两者之间的颜色他们。然后我添加了一个幻影 geom_rect() 它实际上并没有出现在任何地方,但它允许在图例中添加一个额外的条目。

# do colors
adjustcolor("red", alpha.f = 0.1) -> red.tra
adjustcolor("blue", alpha.f = 0.1) -> blue.tra
colfunc <- colorRampPalette(c(red.tra, blue.tra))
purp.tra <- colfunc(3)[2]
adjustcolor(purp.tra, alpha.f = 0.1) -> purp.tra

# plot
ggplot(data = data) +
geom_rect(data = data %>% filter(unclear==0), aes(xmin=start, xmax=stop, ymin=0, ymax=0.7, fill="one")) +
geom_rect(data = data, aes(xmin=start, xmax=stop, ymin=0, ymax=0, fill="one and a half")) +
geom_rect(data = data %>% filter(unclear==1), aes(xmin=start, xmax=stop, ymin=0, ymax=0.7, fill="two"))+
scale_fill_manual("colors",values=c(red.tra, purp.tra, blue.tra), labels=c("one", "one and a half", "two"))+
facet_wrap(~group, ncol = 1, strip.position = "left")

enter image description here

关于r - 将额外的图例项添加到 ggplot2 以进行重叠填充 (geom_rect),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74724700/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com