为什么geom_density在情节的开头形成一个人工峰值,这在基础地块中是看不到的

时间:2015-09-02 09:34:42

标签: r ggplot2

以下代码生成两个密度图,首先使用R基础图形,第二个使用ggplot2。第二个图在曲线的开始处具有人工峰值,这在第一个图中不存在。当x轴极限的开始设置为大于零时,始终存在起始峰值。为什么ggplot会达到这个峰值以及如何避免它呢?

由于缺乏声誉点,我无法发布图片。请自己动手吧。这段代码应该按原样运行。

library(ggplot2)
set.seed(101)
xval<-rlnorm(n=10000)
xdf<-data.frame(xval)

plot(density(xdf$xval), xlim=c(1, 10))
ggplot(data=xdf, aes(x=xval))+geom_density()+xlim(1, 10)

这是ggplot2中的错误吗?

1 个答案:

答案 0 :(得分:1)

如果您更改xlim()的{​​{1}},则可以:

coord_cartesian()

enter image description here

library(ggplot2)
set.seed(101)
xval <- rlnorm(n=10000)
xdf <- data.frame(xval)

par(xaxs = "i") # change the style to fix exact x limits to (1, 10)
plot(density(xdf$xval), xlim = c(1, 10))

enter image description here