我有以下情况:

### GENERATING DATA

set.seed(123)

x1 = rnorm(1000)            
x2 = rnorm(1000)
z = 1 + 2*x1 + 3*x2        
pr = 1/(1+exp(-z))         
y = pr > 0.5               
y1 = ifelse(y == "TRUE", 1, 0)

ex = data.frame(y = y, y1 = y1, x1 = x1, x2 = x2)


### PLOTING THE BINOMIAL REGRESSION

library(ggplot2)

ggplot(ex, aes(x=x1, y=y1)) + 
  geom_point(alpha = 0.2, cex = 3) +
  stat_smooth(method="glm", se=T, method.args = list(family=binomial)) +
  geom_density(data = ex[ex$y1 == 0,], aes(x = x1, y = ..density..),
               alpha = 0.2, fill = "tomato") +
  theme_bw()

此代码为我提供了:

enter image description here

I need to add an inverted density plot for upper points,大概是这样的(我试着使用下面的图像代码,here可用,但没有成功):

enter image description here

谢谢!

推荐答案

一种 Select 是使用geom_polygonstat="density",我们可以使用after_stat(1 - density)来反转密度.此外,我为黑色轮廓添加了geom_path(geom_polygon也将连接端点):

library(ggplot2)

ggplot(ex, aes(x = x1, y = y1)) +
  geom_point(alpha = 0.2, cex = 3) +
  stat_smooth(method = "glm", se = T, method.args = list(family = binomial)) +
  geom_density(
    data = ex[ex$y1 == 0, ], aes(x = x1, y = after_stat(density)),
    alpha = 0.2, fill = "tomato"
  ) +
  geom_polygon(
    data = ex[ex$y, ], aes(x = x1, y = after_stat(1 - density)),
    alpha = 0.2, fill = "blue", stat = "density"
  ) +
  geom_path(
    data = ex[ex$y, ], aes(x = x1, y = after_stat(1 - density)),
    stat = "density", color = "black"
  ) +
  theme_bw()
#> `geom_smooth()` using formula = 'y ~ x'

R相关问答推荐

在Julia中调用R函数

geom_raster不适用于x比例中超过2,15的值

编码变量a、b、c以匹配来自另一个数据点的变量x

从有序数据中随机抽样

如何将在HW上运行的R中的消息(错误、警告等)作为批处理任务输出

如何从R中的字符串元素中减go 一个数字?

如何动态更新selectizeInput?

如何在ggplot图中找到第二轴的比例

使用外部文件分配变量名及其值

一小时满足条件的日期的 Select

如何通过ggplot2添加短轴和删除长轴?

根据1个变量绘制 colored颜色 发散的 map ,由另一个变量绘制饱和度,ggplot2不工作

识别连接的子网(R-igraph)

有没有办法定制Plot(allEffects())面板标题?

将多个列合并为一个列的有效方法是什么?

随机 Select 的非NA列的行均数

R try Catch in the loop-跳过缺少的值并创建一个DF,显示跳过的内容

排序R矩阵的行和列

如何在刻面和翻转堆叠条形图中对齐geom_text()

在使用ggplot2的情况下,如何在使用coord_trans函数的同时,根据未转换的坐标比来定位geom_瓷砖?