Skip to content

Instantly share code, notes, and snippets.

@gshotwell
Last active December 3, 2020 13:28
Show Gist options
  • Save gshotwell/dab97e953763a8b1490e7a2fa5617e7e to your computer and use it in GitHub Desktop.
Save gshotwell/dab97e953763a8b1490e7a2fa5617e7e to your computer and use it in GitHub Desktop.
Lolliplot
library(tidyverse)
survey <- tibble::tribble(
~id, ~q_1, ~q_2, ~q_3,
1L, "good", "bad", "neutral",
2L, "neutral", "good", "neutral",
3L, "bad", "neutral", "neutral",
4L, "neutral", "good", "neutral",
5L, "bad", "good", "neutral",
6L, "bad", "bad", "neutral"
)
plot_df <- survey %>%
pivot_longer(-id, names_to = "question", values_to = "answer") %>%
group_by(answer) %>%
tally()
ggplot(plot_df, aes(x = answer, y = n)) +
geom_point() +
geom_segment( aes(x=answer, xend=answer, y=0, yend=n))
## Faceting by question
plot_df <- survey %>%
pivot_longer(-id, names_to = "question", values_to = "answer", values_drop_na = FALSE) %>%
group_by(answer, question) %>%
count(.drop = FALSE)
ggplot(plot_df, aes(x = answer, y = n)) +
geom_point() +
geom_segment( aes(x=answer, xend=answer, y=0, yend=n)) +
facet_wrap(~question)
## Filtering by question
# Doesn't work!
plot_df %>%
filter(question == "q_3") %>%
ggplot(aes(x = answer, y = n)) +
geom_point() +
geom_segment( aes(x=answer, xend=answer, y=0, yend=n)) +
facet_wrap(~question)
# Works!
plot_df %>%
mutate(answer = as.factor(answer)) %>%
filter(question == "q_3") %>%
ggplot(aes(x = answer, y = n)) +
geom_segment( aes(x=answer, xend=answer, y=0, yend=n)) +
scale_x_discrete(drop = FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment