R语言 ggplot修复图例

qvtsj1bj  于 2023-10-13  发布在  其他
关注(0)|答案(1)|浏览(102)
set.seed(1)
DATA = data.frame(STUDENT = c(1:100),
                  SCORE = sample(1:1000))

如果我运行下面的代码,我会生成许多图,但图例/比例每次都在变化,我如何使它保持不变?

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

oyxsuwqo

oyxsuwqo1#

要获得相同的图例,您可以固定比例尺的limits=,例如。使用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()

相关问题