Skip to content

Instantly share code, notes, and snippets.

@tamaracha
Created June 7, 2020 22:08
Show Gist options
  • Save tamaracha/1c08851548e101a21aa0194c3fc9d013 to your computer and use it in GitHub Desktop.
Save tamaracha/1c08851548e101a21aa0194c3fc9d013 to your computer and use it in GitHub Desktop.
How to import printed tone audiograms in R and plot them with ggplot2
library(magrittr)
# Frequencies tested in tone audiograms
audiogram_frequencies <- c(0.125, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8)
# Simulate hearing loss data in wide format
sample_df <- data.frame(
frequency = audiogram_frequencies,
air_right = sample(40:70, size = 11),
air_left = sample(50:90, size = 11),
bone_right = sample(0:30, size = 11),
bone_left = sample(0:30, size = 11)
) %>%
# Transform into tidy data (long) format
# The original data set stores information about conduction and side in
# variable names,, but we want this information to be encoded in factors.
# In fact, there is just one measurement, the hearing loss,
# which depends on the frequency, conduction, and side factors.
tidyr::pivot_longer(
cols = air_right:bone_left,
names_to = c("conduction", "side"),
names_sep = "_",
names_transform = list(
conduction = ~ factor(.x, levels = c("air", "bone")),
side = ~ factor(.x, levels = c("right", "left"))
),
values_to = "hl"
) %>%
# Drop rows with missing values
tidyr::drop_na(hl) %>%
# Plot data as audiogram
ggplot2::ggplot(
ggplot2::aes(
x = .data$frequency, y = .data$hl,
group = .data$conduction, color = .data$side
)
) +
ggplot2::geom_point(
ggplot2::aes(shape = forcats::fct_cross(.data$conduction, .data$side)),
size = 4
) +
ggplot2::geom_line(ggplot2::aes(linetype = .data$conduction)) +
ggplot2::scale_x_continuous(
breaks = audiogram_frequencies,
labels = paste(audiogram_frequencies),
minor_breaks = NULL,
trans = "log"
) +
ggplot2::scale_y_reverse(
breaks = seq(-10, 100, 10),
minor_breaks = NULL
) +
ggplot2::scale_shape_manual(
values = c(">", "o", "<", "x"),
breaks = c("bone:right", "air:right", "bone:left", "air:left")
) +
ggplot2::expand_limits(y = c(-10, 100)) +
ggplot2::facet_wrap(ggplot2::vars(.data$side)) +
ggplot2::labs(
x = "Frequency in kHz",
y = "Hearing loss in dB (HL)",
shape = "side X conduction"
) +
ggplot2::theme_bw()
ggplot2::ggsave("audiogram.pdf")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment