根据因素使用不同的比例作为填充 [英] Using different scales as fill based on factor

查看:90
本文介绍了根据因素使用不同的比例作为填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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=.3, geom="polygon")

这会根据像这样的因子创建一个填充轮廓图。

This creates a filled contour plot based on factor like so.

I' d喜欢对每个轮廓使用不同的填充比例,使得g = 0时有红色填充,而g = 1时有蓝色填充。这是可能的,如果是这样的话,怎么样?

I'd like to use a different fill scale for each contour, such that g=0 has a red fill while g=1 has a blue fill. Is this possible and if so, how?

推荐答案

这里通过设置 scale_fill_continuous 中的颜色创建两个具有不同< fill >调色板 - 一个红色和一个蓝色 - 的调色板对象。在'红'情节对象中,属于其中一组的行中的红色填充颜色将被蓝色情节对象中相应行的蓝色替换。

Here two plot objects with different fill colour palettes - one red and one blue - are created by setting colours in scale_fill_continuous. In the 'red' plot object, the red fill colours in rows belonging to one of the groups, are replaced with blue colours from the corresponding rows in the 'blue' plot object.

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)

这篇关于根据因素使用不同的比例作为填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆