ggplot Fix Legend

set.seed(1)
DATA = data.frame(STUDENT = c(1:100),
                  SCORE = sample(1:1000))

If I run this code below I generate many graph but the legend/scale changes every time, how do I make it stay the same?

DATA %>%
  sample_n(10) %>%
  ggplot() +
  aes(x = STUDENT, y = SCORE, color = SCORE) + 
  geom_point() +
  scale_color_gradientn(colours = rainbow(5))

enter image description here

enter image description here

>Solution :

To get the same legend you can fix the limits= of the scale, e.g. using limits = c(1, 1000):

set.seed(1)
DATA <- data.frame(
  STUDENT = c(1:100),
  SCORE = sample(1:1000)
)

library(ggplot2)
library(dplyr, warn = FALSE)

make_plot <- function() {
  DATA %>%
    sample_n(10) %>%
    ggplot() +
    aes(x = STUDENT, y = SCORE, color = SCORE) +
    geom_point() +
    scale_color_gradientn(
      colours = rainbow(5),
      limits = c(1, 1000)
    )
}

make_plot()


make_plot()

Leave a Reply