简体   繁体   English

R:ggplot2中的密度图与密度图

[英]R: Density plot vs Density plot in ggplot2

I am trying to do some density plots in R. I originally used density plot but I changed to the density plot in ggplot2 because I visually prefer ggplot2. 我试图在R中做一些密度图。我最初使用密度图,但由于在视觉上更喜欢ggplot2,所以我改成了ggplot2中的密度图。

So I did a density plot using the density plot function and did a density plot in ggplot2 (see below) but I found the plots were not identical. 因此,我使用密度图函数绘制了密度图,并在ggplot2中进行了密度图(请参见下文),但是我发现这些图并不相同。 It looks like some of the y-values have been lost or dropped in the ggplot2 (right plot). 似乎ggplot2中的某些y值丢失或丢失(右图)。 Is there any particular reason for this? 有什么特殊原因吗? How can I make the ggplot identical to the destiny plot (left plot). 我如何使ggplot与命运图相同(左图)。

在此处输入图片说明

Code: 码:

library(ggplot2)
library(grid)
par(mfrow=c(1,2))

# define function to create multi-plot setup (nrow, ncol)
vp.setup <- function(x,y){
 grid.newpage()
 pushViewport(viewport(layout = grid.layout(x,y)))
}

# define function to easily access layout (row, col)
vp.layout <- function(x,y){
  viewport(layout.pos.row=x, layout.pos.col=y)
}


vp.setup(1,2)

dat <- read.table(textConnection("
low high
10611.0 14195.0
10759.0 14437.0
10807.0 14574.0
10714.0 14380.0
10768.0 14448.0
10601.0 14239.0
10579.0 14218.0
10806.0 14510.0
"), header=TRUE, sep="\t")

plot(density(dat$low))

dat.low = data.frame(low2 = c(dat$low), lines = rep(c("low")))

low_plot_gg = (ggplot(dat.low, aes(x = low2, fill = lines)) +
 stat_density(aes(y = ..density..)) + 
 coord_cartesian(xlim = c(10300, 11000)) 
)
print(low_plot_gg, vp=vp.layout(1,2))

Based on some trial and error, it looks like you want 根据反复试验,看起来像您想要的

 + xlim(c(10300,11000))

rather than 而不是

 + coord_cartesian(xlim = c(10300, 11000)) 

coord_cartesian extends the limits of the plots but doesn't change what's drawn inside them at all ... coord_cartesian扩展了图的范围,但完全不改变其内部绘制的内容...

It's not a problem of lost values. 这不是价值损失的问题。 The function plot(density()) proceed to smoothing for extreme value but it's not very accurate for your little dataset. 函数plot(density())进行平滑以求出极值,但是对于您的小数据集来说不是很准确。 For a bigger dataset the two plots will be the same. 对于更大的数据集,两个图将相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM