如何在ggplot2中绘制修剪后的密度图而不会丢失部分 [英] How to draw a clipped density plot in ggplot2 without missing sections
问题描述
我想用ggplot2绘制一个由不同方法产生的密度的格子图,其中使用了相同的yaxis尺度。
我想对于任何一种方法,将y轴的上限设置为低于最高密度值的值。不过,ggplot默认会删除绘图区域外的几何图形部分。
例如:
#问题的玩具示例
xval < - rnorm(10000)
#Base1
plot(density(xval))
#Base2
plot(density(xval) ,ylim = c(0,0.3))#密度> 0.3未从绘图中删除
xval < - as.data.frame(xval)
ggplot(xval,aes(x = xval))+ geom_density()#gg1 - 看起来像Base1
ggplot(xval,aex(x = xval))+ geom_density()+ ylim(0,0.3)
#gg2:由于去除密度值而看起来不像Base2> 0.3
以下图片产生:
如何让ggplot图片没有缺失部分?
xlim()
将丢弃所有不在指定范围内的数据点。这产生密度图的不连续性。使用 coord_cartesian()
进行放大而不会丢失数据点。 ggplot(xval,aes(x = xval))+
geom_density()+
coord_cartesian ylim = c(0,0.3))
I would like to use ggplot2 to draw a lattice plot of densities produced from different methods, in which the same yaxis scale is used throughout.
I would like to set the upper limit of the y axis to a value below the highest density value for any one method. However ggplot by default removes sections of the geom that are outside of the plotted region.
For example:
# Toy example of problem
xval <- rnorm(10000)
#Base1
plot(density(xval))
#Base2
plot(density(xval), ylim=c(0, 0.3)) # densities > 0.3 not removed from plot
xval <- as.data.frame(xval)
ggplot(xval, aes(x=xval)) + geom_density() #gg1 - looks like Base1
ggplot(xval, aex(x=xval)) + geom_density() + ylim(0, 0.3)
#gg2: does not look like Base2 due to removal of density values > 0.3
These produce the images below:
How can I make the ggplot image not have the missing section?
Using xlim()
or ylim()
directly will drop all data points that are not within the specified range. This yields the discontinuity of the density plot. Use coord_cartesian()
to zoom in without losing the data points.
ggplot(xval, aes(x=xval)) +
geom_density() +
coord_cartesian(ylim = c(0, 0.3))
这篇关于如何在ggplot2中绘制修剪后的密度图而不会丢失部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!