gpt4 book ai didi

r - 在循环内的 ggplot 中生成一致的动态调色板?

转载 作者:行者123 更新时间:2023-12-04 06:38:23 27 4
gpt4 key购买 nike

我有一个名为 d1 的数据集,类似于:

location, depth.from, depth.to, val, type 

我有一个循环,可以为每个独特的位置创建一个相当复杂的图(它使用 grid.arrange 将许多东西粘合在一起,这就是为什么我不能在该位置使用 facet_wrap 以保持图例/颜色的一部分一致剧情)。

假设“类型”有 4 个类别,当一个位置的“类型”数量与另一个位置不同时,每个图之间分配的颜色不一致。我可以手动强制它们相同,但我试图概括这个功能。谷歌让我失望了。

对于以下块,d1 是基于位置类型的数据子集,例如
d1 <- subset(myData, location == location.list[i])

查看在循环内的情节:
p1 <- ggplot(data = d1, aes (y=val, x=depth.from))+
layer(geom = "point", size = 2) +
geom_rect(data=d1, aes(xmin=Depth.to, xmax=Depth.from, ymin=0, ymax=100, fill = type), linetype =0, alpha=0.3)+
scale_fill_brewer(palette="Set1")

geom_rect 命令正在遍历数据并基于深度和深度,创建基于填充类型的叠加层。我可以用 scale_fill_manual("Lith", c("Val1" = "DodgerBlue4"...)等手动设置它,但这违背了目的。如果我有:类型就像我想要的东西:
Bird_one = blue
Bird_two = red
Bird_three = green

我要 bird_three绿色,即使 bird_two不存在,无需使用 scale_fill_manual 显式设置它.有没有办法为调色板设置全局名称列表?也许通过从以下内容提供数组:
myData <- read.csv("mydata.csv" 
typeList <- unique(myData$type)

最佳答案

很晚了,但实际上通过设置 scale_fill_discrete(drop=F) 有一个微不足道的解决方案

plots <- lapply(dfs, function(df) {
ggplot(df,
aes(
x=location, fill=type,
y=(depth.from + depth.to) / 2,
ymin=depth.from, ymax=depth.to
) ) +
geom_crossbar() + scale_fill_discrete(drop=F)
})
library(gridExtra)
do.call(grid.arrange, plots)

enter image description here

这是我使用的虚拟数据:
set.seed(12)
items <- 2
dfs <-
replicate(2, simplify=F,
data.frame(
location=sample(letters, items),
depth.from=runif(items, -10, -5),
depth.to=runif(items, 5, 10),
val=runif(items),
type=factor(
sample(c("Bird_one", "Bird_two", "Bird_three"), items),
levels=c("Bird_one", "Bird_two", "Bird_three")
) ) )

关于r - 在循环内的 ggplot 中生成一致的动态调色板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21322819/

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