Prradep
Prradep

Reputation: 5716

plotting: color based on the combination of two column levels

How to plot based on the combination of two column levels(here: treatment, replicate)?

set.seed(0)
x <- rep(1:10, 4)
y <- sample(c(rep(1:10, 2)+rnorm(20)/5, rep(6:15, 2) + rnorm(20)/5))
treatment <- sample(gl(8, 5, 40, labels=letters[1:8]))
replicate <- sample(gl(8, 5, 40))
d <- data.frame(x=x, y=y, treatment=treatment, replicate=replicate)

plots: color based on single column levels

ggplot(d, aes(x=x, y=y, colour=treatment)) + geom_point()

output

ggplot(d, aes(x=x, y=y, colour=replicate)) + geom_point() 

output

The combination of two column levels would be a-1, a-2, a-3, ... h-6, h-7, h-8.

Upvotes: 2

Views: 7856

Answers (1)

eipi10
eipi10

Reputation: 93851

64 colours will be uninterpretable. How about point labels instead:

ggplot(d, aes(x=x, y=y, colour=treatment)) + 
  geom_text(aes(label=paste0(treatment, replicate)), size=3, show.legend=FALSE) +
  theme_classic()

enter image description here

Or, if you're trying to spot differences in patterns for different treatments, maybe faceting would help:

ggplot(d, aes(x=x, y=y, colour=treatment)) + 
  geom_text(aes(label=paste0(treatment, replicate)), size=3, show.legend=FALSE) +
  facet_wrap(~ treatment, ncol=4) +
  scale_x_continuous(expand=c(0,0.7)) +
  theme_bw() + theme(panel.grid=element_blank())

enter image description here

But, if you really want a whole bunch of colours...

ggplot(d, aes(x=x, y=y, colour=interaction(treatment,replicate,sep="-",lex.order=TRUE))) + 
  geom_point() +
  labs(colour="Treatment-Replicate") +
  theme_classic()

(If you want all potential treatment-replicate combinations to be listed in the legend, regardless of whether they're present in the data, then add + scale_colour_discrete(drop=FALSE) to the plot code.)

enter image description here

Upvotes: 6

Related Questions