Guest User

Untitled

a guest
Feb 22nd, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. # Limit factor levels displayed in ggplot2 legend
  2. # When using many factor levels, the legend can become too large to be useful
  3. # We want to pair back the legend to something readable, with less detail.
  4.  
  5. # For our minimally reproducible example, we will create a series of 40 sinusoidal
  6. # curves that are slightly offset from each other, then plot each one in a different
  7. # color. The resulting plot will have a somewhat rainbow look, but the legend will
  8. # contain 40 labels; we want to reduce this to about 5 labels in the legend.
  9.  
  10. # Libraries used
  11. library(dplyr)
  12. library(ggplot2)
  13.  
  14. # Create some data for demonstration purposes (minimal reproducible example)
  15. base_curve <- sin(x = seq(0, 2*pi, by = 0.05))
  16. multipliers <- rep(seq(from = 0, to = 1, by = 0.025), each = length(base_curve))
  17. rep_times <- length(multipliers) / length(base_curve)
  18. base_curve <- rep(base_curve, times = rep_times)
  19.  
  20. my_df <- data_frame(base_curve,
  21. multipliers) %>%
  22. mutate(curve = base_curve + multipliers,
  23. mult_fact = as.factor(multipliers),
  24. index = rep(seq(0, 2*pi, by = 0.05), times = rep_times))
  25.  
  26. # Plot the data with ggplot
  27. my_df %>%
  28. ggplot(aes(x = index, y = curve, color = mult_fact)) +
  29. geom_line() +
  30. scale_color_discrete(breaks = c(0, 0.2, 0.4, 0.8, 1))
  31.  
  32. # Run the plot again without scale_color_discrete() to see how the legend
  33. # is too detailed and visually busy
Add Comment
Please, Sign In to add comment