How to assign colors to categorical variables in ggplot2 that have stable mapping?

后端 未结 5 842
[愿得一人]
[愿得一人] 2020-11-22 08:46

I\'ve been getting up to speed with R in the last month.

Here is my question:

What is a good way to assign colors to categorical variables in ggplot2 that ha

5条回答
  •  名媛妹妹
    2020-11-22 08:55

    The easiest solution is to convert your categorical variable to a factor prior to the subsetting. Bottomline is that you need a factor variable with exact the same levels in all your subsets.

    library(ggplot2)
    dataset <- data.frame(category = rep(LETTERS[1:5], 100), 
        x = rnorm(500, mean = rep(1:5, 100)), y = rnorm(500, mean = rep(1:5, 100)))
    dataset$fCategory <- factor(dataset$category)
    subdata <- subset(dataset, category %in% c("A", "D", "E"))
    

    With a character variable

    ggplot(dataset, aes(x = x, y = y, colour = category)) + geom_point()
    ggplot(subdata, aes(x = x, y = y, colour = category)) + geom_point()
    

    With a factor variable

    ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
    ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()
    

提交回复
热议问题