Last active
April 9, 2024 10:25
-
-
Save mgrabovsky/2104a47fbb7264071ac8992906074088 to your computer and use it in GitHub Desktop.
Simulating observations in the Lighthouse problem in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
# Metaparameters. | |
d <- 5 # Distance of the lighthouse from the coast. | |
x0 <- 4 # Perpendicular position of the lighthouse along the coast. | |
set.seed(1987) | |
# Simulate the data. | |
N <- 1e4 | |
phi <- runif(N, -pi / 2, pi / 2) | |
x <- d * tan(phi) + x0 | |
df_sims <- tibble(x = x) | |
# Plot the distribution. | |
ggplot(df_sims, aes(x, after_stat(density))) + | |
geom_density(colour = "sienna3", linewidth = 1) + | |
geom_histogram(binwidth = 1, center = .5, fill = "slategrey", colour = "white") + | |
geom_vline(xintercept = x0, colour = "goldenrod1", linetype = 2, linewidth = .8) + | |
xlim(-40, 50) + | |
theme_minimal() | |
# Distribution of absolute deviations from the median. | |
absolute_deviation <- abs(x - median(x)) | |
mad_obs <- median(absolute_deviation) | |
df_absdev <- tibble(absolute_deviation = absolute_deviation) | |
ggplot(df_absdev, aes(absolute_deviation, after_stat(density))) + | |
geom_histogram(binwidth = 1, center = .5, fill = "sienna3", colour = "white") + | |
geom_vline(xintercept = mad_obs, colour = "slategrey", linetype = 2, linewidth = 1) + | |
annotate("text", x = mad_obs + 1.3, y = 0.114, | |
label = "Median absolute deviation", | |
colour = "slategrey", size = 3.5, hjust = 0) + | |
xlim(0, 60) + | |
theme_minimal() | |
ggplot(df_absdev, aes(absolute_deviation, after_stat(y))) + | |
stat_ecdf(colour = 'sienna3') + | |
geom_vline(xintercept = mad_obs, colour = "slategrey", linetype = 2, linewidth = 1) + | |
annotate("text", x = mad_obs + 1.3, y = 0.114, | |
label = "Median absolute deviation", | |
colour = "slategrey", size = 3.5, hjust = 0) + | |
scale_x_log10() + | |
ylab("Cumulative density") + | |
theme_minimal() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment