I was wondering if I could plot the reflection of my "Density Histogram" (i.e., shadow [as shown in "blue" in the below picture]) in (possibly) "Base" R?
我想知道我是否可以在(可能)“Base”R中绘制我的“密度直方图”的反射(即阴影[如下图中“蓝色”所示])?
Please see my R code below the picture.
Here is my R code:
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) )
1 个解决方案
#1
1
You can do something like this using ggplot2
by extracting the values from a histogram, creating negative values and plotting as columns.
您可以使用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")
EDIT: and here's a base R solution.
编辑:这是一个基础R解决方案。
h1 <- hist(rnorm(1e4))
h2 <- h1
h2$counts <- -h1$counts
plot(h1, ylim = c(-2000, 2000))
lines(h2, col = "blue")
#1
1
You can do something like this using ggplot2
by extracting the values from a histogram, creating negative values and plotting as columns.
您可以使用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")
EDIT: and here's a base R solution.
编辑:这是一个基础R解决方案。
h1 <- hist(rnorm(1e4))
h2 <- h1
h2$counts <- -h1$counts
plot(h1, ylim = c(-2000, 2000))
lines(h2, col = "blue")