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

后端 未结 5 843
[愿得一人]
[愿得一人] 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 09:01

    I am in the same situation pointed out by malcook in his comment: unfortunately the answer by Thierry does not work with ggplot2 version 0.9.3.1.

    png("figure_%d.png")
    set.seed(2014)
    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"))
    
    ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
    ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()
    

    Here it is the first figure:

    ggplot A-E, mixed colors

    and the second figure:

    ggplot ADE, mixed colors

    As we can see the colors do not stay fixed, for example E switches from magenta to blu.

    As suggested by malcook in his comment and by hadley in his comment the code which uses limits works properly:

    ggplot(subdata, aes(x = x, y = y, colour = fCategory)) +       
        geom_point() + 
        scale_colour_discrete(drop=TRUE,
            limits = levels(dataset$fCategory))
    

    gives the following figure, which is correct:

    correct ggplot

    This is the output from sessionInfo():

    R version 3.0.2 (2013-09-25)
    Platform: x86_64-pc-linux-gnu (64-bit)
    
    locale:
     [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
     [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
     [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
     [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
     [9] LC_ADDRESS=C               LC_TELEPHONE=C            
    [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
    
    attached base packages:
    [1] methods   stats     graphics  grDevices utils     datasets  base     
    
    other attached packages:
    [1] ggplot2_0.9.3.1
    
    loaded via a namespace (and not attached):
     [1] colorspace_1.2-4   dichromat_2.0-0    digest_0.6.4       grid_3.0.2        
     [5] gtable_0.1.2       labeling_0.2       MASS_7.3-29        munsell_0.4.2     
     [9] plyr_1.8           proto_0.3-10       RColorBrewer_1.0-5 reshape2_1.2.2    
    [13] scales_0.2.3       stringr_0.6.2 
    

提交回复
热议问题