在 R 中绘制直方图的反射(即阴影)(提供代码和视觉效果)

Plotting the reflection (i.e., shadow) of a histogram in R (code and visual provided)

我想知道我是否可以绘制“密度直方图”的 反映(即 shadow [如下图“蓝色”所示]) in (possibly) "Base" R ?

请看图片下方我的R代码

这是我的 R 代码:

set.seed(0)  ;  x = rnorm(n = 1e4)  ;  den = density(x)

plot(  den$x , den$y , ty = 'n' , ylim = c( -max(den$y), max(den$y) ) , xlim = c(min(den$x), max(den$x)) )

b = hist(x, freq = F , ylim = c( -max(den$y), max(den$y) ), main = NA  )

polygon( c(den$x, den$x) , c(den$y, -den$y) )

您可以使用 ggplot2 通过从直方图中提取值、创建负值并绘制为列来执行 某些操作

library(ggplot2)
df1 <- data.frame(x = rnorm(1e4))
p  <- ggplot(df1) + geom_histogram(aes(x = x))
pg <- ggplot_build(p)
pg <- pg$data[[1]]
pg$mirror <- -pg$count
ggplot(pg) + geom_col(aes(x, y)) + geom_col(aes(x, mirror), fill = "blue")

编辑:这是一个基本的 R 解决方案。

h1 <- hist(rnorm(1e4))
h2 <- h1
h2$counts <- -h1$counts
plot(h1, ylim = c(-2000, 2000))
lines(h2, col = "blue")