Plot density and cumulative density function in one combined plot using ggplot2

試著忘記壹切 提交于 2019-12-05 07:00:35

问题


I would like to get a plot that combines the density of observations and the cdf.

The usual problem with that is that the scales of the two are way off. How can this be remedied, i.e., two scales be used or, alternatively, one of the data series be rescaled (preferably within ggplot, as I would like to separate computation and display of data).

Here's the code so far:

>dput(tmp) yields

structure(list(drivenkm = c(8, 11, 21, 4, 594, 179, 19, 7, 10, 36)), .Names = "drivenkm", class = c("data.table", "data.frame" ), row.names = c(NA, -10L), .internal.selfref = <pointer: 0x223cb78>)

then I do

p = ggplot(data = tmp, aes(x = drivenkm)) + geom_histogram(aes(y = ..density..), alpha = 0.2, binwidth = 3) + stat_ecdf(aes(x = drivenkm)); print(p)

What I get is the following:

Obviously, the scales are way off. How can this be fixed, such that both the histogram and the cdf can be interpreted in a sensible way?

Thanks!


回答1:


The density is scaled by the binwidth so the area sums to 1. So the y for your histogram should be multiplied by this too:

p = ggplot(data = tmp, aes(x = drivenkm)) +
   geom_histogram(aes(y = 3*..density..), alpha = 0.2, binwidth = 3) +
   stat_ecdf(aes(x = drivenkm))



来源:https://stackoverflow.com/questions/21109567/plot-density-and-cumulative-density-function-in-one-combined-plot-using-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!