首页 > 解决方案 > Geom_density_2d_filled() ggplot:(1)如何围绕所有点绘制轮廓,(2)如何改变渐变颜色?

问题描述

我有两个问题,我无法弄清楚我们的谷歌:

数据和ggplot:

x = rnorm(n = 500, mean = 0.5, sd = 0.3)
y = rnorm(n = 500, mean = 6, sd = 1)
data = merge(x, y, by = "row.names", all = TRUE)

data %>% ggplot(aes(x, y))+
  geom_density_2d_filled(contour_var = "ndensity", bins = 5)+
  theme_classic()

ggplot

(1)如何围绕所有点绘制轮廓?目前,20% 的值与背景颜色相同。应该添加新层?

(2) 如何将背景颜色更改为白色,并将渐变颜色更改为 brewer "Blues" 调色板(所有高于 0 的值都应具有与白色背景不同的蓝色)?

标签: rggplot2

解决方案


You'd probably want to decouple the stat from the geom, as the geom_density_2d_filled() draws polygons but also includes the outer layer as a rectangle.

Here is my suggestion:

x = rnorm(n = 500, mean = 0.5, sd = 0.3)
y = rnorm(n = 500, mean = 6, sd = 1)
data = merge(x, y, by = "row.names", all = TRUE)

data %>% ggplot(aes(x, y))+
  stat_density_2d(geom = "polygon", contour = TRUE,
                  aes(fill = after_stat(level)), colour = "black",
                  bins = 5) +
  scale_fill_distiller(palette = "Blues", direction = 1) +
  theme_classic()

enter image description here


推荐阅读