I have the following dataframe df_long:
set.seed(123) # For reproducibility
df_long <- data.frame(
trait = rep(c("Trait1", "Trait2", "Trait3", "Trait4", "Trait5"), each = 4),
type = rep(c("eur_ita", "eur_ita_2", "eur_ita_3", "eur_ita_4"), times = 5),
value = c(runif(5, 5, 15), runif(5, 8, 20), runif(5, 1, 12), runif(5, 4, 18)),
macro_cat3 = rep(c("Category1", "Category2"), each = 10) # Dividing into two macro categories
)
and I wrote the following code to make a lollipop plot:
ggplot(df_long, aes(x = trait, y = value, color = type, shape = type, alpha = type)) +
# Add the lollipop stems
geom_segment(
aes(x = trait, xend = trait, y = 0, yend = value),
position = position_dodge(width = 0.8), # Dodge stems horizontally
linewidth = 0.6 # Adjust stem thickness
) +
# Add the lollipop heads
geom_point(
position = position_dodge(width = 0.8), # Dodge points horizontally
size = 3 # Adjust point size
) +
facet_wrap(~ macro_cat3, scales = "free_x", ncol = 4) +
labs(x = "Trait", y = "Percentage of r2", color = "Type", shape = "Type", alpha = "PRS Type") +
scale_color_manual(
values = c(
"eur_ita" = "red",
"eur_ita_2" = "black",
"eur_ita_3" = "green",
"eur_ita_4" = "gray"
)
) +
scale_alpha_manual(
values = c(
"eur_ita" = 1,
"eur_ita_2" = 0.9,
"eur_ita_3" = 0.9,
"eur_ita_4" = 1
),
guide = "none"
) +
scale_shape_manual(
values = c(
"eur_ita" = 18,
"eur_ita_2" = 18,
"eur_ita_3" = 19,
"eur_ita_4" = 19
)
) +
theme_minimal() +
theme(
axis.text.x = element_text(angle = 45, hjust = 1, size = 10),
strip.text = element_text(size = 12),
legend.position = "bottom",
panel.border = element_rect(color = "black", fill = NA, linewidth = 0.8),
strip.background = element_blank()
)
and I got the attached image as an example.
How can I have a vertical stem per each dot, so as to have 4 lollipops per each x value?
Rather than using geom_segment
, use geom_linerange
For example
geom_linerange(
aes(x = trait, ymin = 0, ymax = value),
position = position_dodge(width = 0.8), # Dodge stems horizontally
linewidth = 0.6 # Adjust stem thickness
)