Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading