library(ggplot2)
set.seed(77) # guarantees identical random data when 'rnorm' command is repeated
dat = data.frame(X = rnorm(300, mean = 2, sd = 3))
str(dat)
## 'data.frame': 300 obs. of 1 variable:
## $ X: num 0.351 5.273 3.919 5.128 2.509 ...
head(dat)
## X
## 1 0.351086
## 2 5.273162
## 3 3.919333
## 4 5.127728
## 5 2.509110
## 6 5.413401
A histogram with counts (not normalised to 1):
ggplot(dat, aes(x = X)) +
geom_histogram(color = "black", fill = "steelblue", binwidth = 0.7) +
labs(x = "x", y = "Frequency") +
ggtitle("Histogram of random variable X") +
theme_minimal()
More explanations on this good site.
Now, we use bins = … instead of binwidth = …, i.e. we fix the number of bins, not their width:
ggplot(dat, aes(x = X, y = after_stat(density))) +
geom_histogram(aes(y = after_stat(density)), color = "black", fill = "steelblue", bins = 30, alpha = 0.7) +
labs(x = "", y = "Frequency") + # axis labels, we leave the x-axis empty here
ggtitle("Histogram of the random variable X") +
geom_density(color = "red", linewidth = 1.0, alpha = 0.5) + # add density curve
theme_minimal()
Note the y = after_stat(density). This normalises to area 1 !
When using ggplot for the density plot, there is no need
to call the density() function. However, if we don’t, we
cannot use the density() function output for further
calculations!
We can use the function ecdf to estimate a cumulative distribution function from measured data. In base R, we call this function and plot the CDF afterwards:
CDF <- ecdf(dat$X) # get the CDF
str(CDF)
## function (v)
## - attr(*, "class")= chr [1:3] "ecdf" "stepfun" "function"
## - attr(*, "call")= language ecdf(dat$X)
plot(CDF, main = "CDF", xlab = "x", ylab = "F(x)", col = "blue", cex = 0.5, font.main = 1)
The CDF object represents a function, but the following plot command “knows” how to treat it.
When using ggplot, there is no need to call
ecdf explicitely. The CDF is calculated internally when the
layer stat_ecdf() is included. The disadvantage is, that we
don’t have the CDF data for further calculations.
ggplot(dat, aes(x = X)) + stat_ecdf(col = "red")
Again, more details here.
Note that all code snippets are designed for comprehensibility, not for efficiency!