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

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

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

假设“类型”有4个类别,当一个位置的“类型”数目与另一位置不同时,分配的颜色在每个图之间不一致的问题。我可以手动强制它们相同,但是我试图对此功能进行概括。 Google让我失败了。

对于以下块,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)

这是我使用的伪数据:
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/

10-11 04:35