根据因子使用不同的比例作为填充

2024-04-05

cnt = 100
df <- data.frame(x = c(rnorm(cnt, mean = 3), rnorm(cnt, mean = 0)),
                 y = rnorm(2 * cnt), g = rep(0:1, each = cnt))

ggplot(df, aes(x, y, color = as.factor(g))) + 
  stat_density2d(aes(fill = ..level..), alpha = 0.3, geom = "polygon")

This creates a filled contour plot based on factor: enter image description here

我想为每个轮廓使用不同的填充比例,例如 g = 0 具有红色填充,而 g = 1 具有蓝色填充。这可能吗?如果可能的话,如何实现?


正如@joran 已经评论的,基本设计ggplot是每一个尺度aes主题。因此需要不同程度的丑陋的解决方法。它们通常涉及创建一个或多个绘图对象、操作对象的各个组件,然后从所操作的对象生成新的绘图。

这里有两个不同的绘图对象fill调色板 - 一种红色和一种蓝色 - 是通过在中设置颜色来创建的scale_fill_continuous。在“红色”绘图对象中,属于其中一组的行中的红色填充颜色将替换为“蓝色”绘图对象中相应行中的蓝色。

library(ggplot2)
library(grid)
library(gtable)

# plot with red fill
p1 <- ggplot(data = df, aes(x, y, color = as.factor(g))) +
  stat_density2d(aes(fill = ..level..), alpha = 0.3, geom = "polygon") +
  scale_fill_continuous(low = "grey", high = "red", space = "Lab", name = "g = 0") +
  scale_colour_discrete(guide = FALSE) +
  theme_classic()

# plot with blue fill
p2 <- ggplot(data = df, aes(x, y, color = as.factor(g))) +
  stat_density2d(aes(fill = ..level..), alpha = 0.3, geom = "polygon") +
  scale_fill_continuous(low = "grey", high = "blue", space = "Lab", name = "g = 1") +
  scale_colour_discrete(guide = FALSE) +
  theme_classic()


# grab plot data
pp1 <- ggplot_build(p1)
pp2 <- ggplot_build(p2)$data[[1]]


# replace red fill colours in pp1 with blue colours from pp2 when group is 2
pp1$data[[1]]$fill[grep(pattern = "^2", pp2$group)] <- pp2$fill[grep(pattern = "^2", pp2$group)]


# build plot grobs
grob1 <- ggplot_gtable(pp1)
grob2 <- ggplotGrob(p2)

# build legend grobs
leg1 <- gtable_filter(grob1, "guide-box") 
leg2 <- gtable_filter(grob2, "guide-box") 
leg <- gtable:::rbind_gtable(leg1[["grobs"]][[1]],  leg2[["grobs"]][[1]], "first")


# replace legend in 'red' plot
grob1$grobs[grob1$layout$name == "guide-box"][[1]] <- leg


# plot
grid.newpage()
grid.draw(grob1)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据因子使用不同的比例作为填充 的相关文章

随机推荐