Fitting a curve to a ggplot histogram
I know that I can fit the density curve to my histogram in ggplot as follows.
df = data.frame(x=rnorm(100)) ggplot(df, aes(x=x, y=..density..)) + geom_histogram() + geom_density()
However, I want my yaxis to be frequency (counts) instead of density and keep a curve that matches the distribution. How to do it?
+3
source to share
1 answer
Depending on your goals, something like this might work by simply scaling the density curve using multiplication:
ggplot(df, aes(x=x)) + geom_histogram() + geom_density(aes(y=..density..*10))
or
ggplot(df, aes(x=x)) + geom_histogram() + geom_density(aes(y=..count../10))
Choose other values (instead of 10) if you want to scale things differently.
Edit:
Since you are defining your scale factor in the global environment, you can define it in aes
:
ggplot(df, aes(x=x)) + geom_histogram() + geom_density(aes(n=n, y=..density..*n))
# or
ggplot(df, aes(x=x, n=n)) + geom_histogram() + geom_density(aes(y=..density..*n))
or another less pleasant way using get
:
ggplot(df, aes(x=x)) +
geom_histogram() +
geom_density(aes(y=..density.. * get("n", pos = .GlobalEnv)))
+2
source to share