我想创建一个二维密度图,其中颜色深度代表密度。
对于数据集
x1 <- rnorm(100, mean=0)
y1 <- rnorm(100, mean=0)
x2 <- rnorm(100, mean=4)
y2 <- rnorm(100, mean=4)
df <- data.frame(x = c(x1, x2), y=c(y1, y2), cat=rep(c("A", "B"), each=100))
我可以画等高线图
ggplot(df, aes(x=x, y=y, color=cat)) + geom_密度2d()
...但我希望图像在 cat="A" 数据的峰值处具有强烈的橙色,而不是轮廓,随着密度的降低而淡出为透明,并在峰值处具有强烈的青色cat="B" 数据的峰值,随着密度的降低而逐渐消失。
似乎
geom_tile()
和aes(alpha=cat)
的某种组合可以做到这一点,但我不太明白。
这样做:
# Create density plot with custom colors for categories A and B
ggplot(df, aes(x = x, y = y)) +
stat_density_2d(
aes(fill = cat, alpha = after_stat(level)),
geom = "polygon",
color = NA
) +
scale_fill_manual(
values = c("A" = "red", "B" = "cornflowerblue"),
name = "Category", # Legend title
guide = "legend"
) +
scale_alpha(range = c(0, 0.7), guide = "none")