Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For simple situations like the exact example in the OP, I agree that Thierry's answer is the best. However, I think it's useful to point out another approach that becomes easier when you're trying to maintain consistent color schemes across multiple data frames that are <em>not</em> all obtained by subsetting a single large data frame. Managing the factors levels in multiple data frames can become tedious if they are being pulled from separate files and not all factor levels appear in each file.</p> <p>One way to address this is to create a custom manual colour scale as follows:</p> <pre><code>#Some test data dat &lt;- data.frame(x=runif(10),y=runif(10), grp = rep(LETTERS[1:5],each = 2),stringsAsFactors = TRUE) #Create a custom color scale library(RColorBrewer) myColors &lt;- brewer.pal(5,"Set1") names(myColors) &lt;- levels(dat$grp) colScale &lt;- scale_colour_manual(name = "grp",values = myColors) </code></pre> <p>and then add the color scale onto the plot as needed:</p> <pre><code>#One plot with all the data p &lt;- ggplot(dat,aes(x,y,colour = grp)) + geom_point() p1 &lt;- p + colScale #A second plot with only four of the levels p2 &lt;- p %+% droplevels(subset(dat[4:10,])) + colScale </code></pre> <p>The first plot looks like this:</p> <p><img src="https://i.stack.imgur.com/IHtqM.png" alt="enter image description here"></p> <p>and the second plot looks like this:</p> <p><img src="https://i.stack.imgur.com/f9flP.png" alt="enter image description here"></p> <p>This way you don't need to remember or check each data frame to see that they have the appropriate levels.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload