2017-05-26 84 views
0

我想知道如果我可以绘制我的“密度直方图”(即,阴影 [的反射(如下图中的“蓝色”所示)])(可能)“Base”R?绘制的直方图的R中的反射(即,阴影)(代码和可视化提供)

请在照片下方看看我的R码。

enter image description here

这里是我的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)) 

回答

1

你可以做一些这样使用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") 

enter image description here

编辑:和这里的基础R溶液。

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

enter image description here

+0

添加了一个基础R溶液。是的,只需在ggplot解决方案的末尾添加'+ coord_flip()'即可。 – neilfws

+0

如果你想要密度,那么你需要使用'density()'做类似的事情。 – neilfws