Created
July 20, 2023 14:38
-
-
Save guidocor/5592cdd90680f44ef2077070b35b13e4 to your computer and use it in GitHub Desktop.
ggplot snippet to show responses as density plots
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
if (!require("pacman")) install.packages("pacman") | |
pacman::p_load("tidyverse", "ggpubr", "see") | |
set.seed(123) | |
n = 100 | |
df = data.frame( | |
part = paste0("id", 1:n), | |
scale_A = rnorm(n, m = 10, sd = 5), | |
# does not work well in Likert type variables | |
scale_B = sample(0:5, n, replace = TRUE, prob = c(0.1, 0.15, 0.4, 0.2, 0.1, 0.05)), | |
scale_C = abs(rnorm(n, m = 0, sd = 5)), | |
scale_D = rnorm(n, m = 10, sd = 5) | |
) | |
# The data-frame must be in long format | |
# the code assumes that columns are adjacent | |
df_long <- df %>% pivot_longer(cols = scale_A:scale_D) %>% | |
# Change the names to a more intruitive ones | |
mutate(name = case_when( | |
name == "scale_A" ~ "A", | |
name == "scale_B" ~ "B", | |
name == "scale_C" ~ "C", | |
name == "scale_D" ~ "D" | |
)) | |
# we specify what we want to plot in aes | |
df_long %>% ggplot(aes(x = value, fill = name)) + | |
# alternative is to use geom_histogram | |
geom_density() + | |
# here we specify that each scale response must be in one facet | |
facet_wrap( ~ name, | |
ncol = 1, # change the numbner of columns to play with disposition | |
scales = "free") + # remove scales = "free" if everything is in te same sclae | |
theme_modern() + | |
# if you prefer without color use the following | |
# scale_fill_manual(values = c("darkgrey","darkgreyk", "darkgrey", "darkgrey")) + | |
scale_fill_manual(values = c("#58d68d","#804a87", "#fc03c2", "#0356fc")) + | |
# labs | |
xlab("") + | |
ylab("Desnsity") + | |
# remove legend as each facet provides the title | |
theme(legend.position = "none", legend.title = element_blank()) + | |
ggtitle("Title of the figure") | |
# saving the plot, you can change size, units and name. By default | |
# it takes the last plot executed | |
ggsave("fig.png", width = 10, height = 10, units = "in") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment