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


i've been getting speed r in last month , first post here. looking forward joining community. here question:

what way assign colors categorical variables in ggplot2 have stable mapping? need consistent colors across set of graphs have different subsets , different number of categorical variables.

for example,

plot1 <- ggplot(data, aes(xdata, ydata,color=categoricalddata)) + geom_line() 

where categoricaldata has 5 levels.

and then

plot2 <- ggplot(data.subset, aes(xdata.subset, ydata.subset,                                   color=categoricalddata.subset)) + geom_line() 

where categoricaldata.subset has 3 levels.

however, particular level in both sets end different color, makes harder read graphs together.

do need create vector of colors in data frame? or there way assigns specific colors categories?

thanks

for simple situations exact example in op, agree thierry's answer best. however, think it's useful point out approach becomes easier when you're trying maintain consistent color schemes across multiple data frames not obtained subsetting single large data frame. managing factors levels in multiple data frames can become tedious if being pulled separate files , not factor levels appear in each file.

one way address create custom manual colour scale follows:

#some test data dat <- data.frame(x=runif(10),y=runif(10),         grp = rep(letters[1:5],each = 2),stringsasfactors = true)  #create custom color scale library(rcolorbrewer) mycolors <- brewer.pal(5,"set1") names(mycolors) <- levels(dat$grp) colscale <- scale_colour_manual(name = "grp",values = mycolors) 

and add color scale onto plot needed:

#one plot data p <- ggplot(dat,aes(x,y,colour = grp)) + geom_point() p1 <- p + colscale  #a second plot 4 of levels p2 <- p %+% droplevels(subset(dat[4:10,])) + colscale 

the first plot looks this:

enter image description here

and second plot looks this:

enter image description here

this way don't need remember or check each data frame see have appropriate levels.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -