thijs van den bergh
thijs van den bergh

Reputation: 618

draw several ablines at once with specific color scheme

I have a data frame with slopes and intercepts coming from a series of simple linear regressions. In plotting the ablines I want to use a color coding that is specific for all possible combinations of class and category.

Say the data frame looks as follows:

(intercept  <-  rnorm(n = 40, mean = 1, sd = 0.25))
(slope      <-  rnorm(n = 40, mean = 2, sd = 1))
(clss       <-  c(rep("a", 20), rep("b", 20)))
(ctg        <-  c(rep("mm", 10), rep("nn", 10), rep("mm", 10), rep("nn", 10)))
df          <-  data.frame(intercept, slope, clss, ctg)

I managed to plot all ablines using:

plot(1, type="n", axes=FALSE, xlab="", ylab="", xlim=c(0, 10), ylim=c(0, 10))
mapply(abline, df$intercept, df$slope)

I want to plot these lines all in say green when clss=="a" and ctg=="mm" and use different colors for the other clss * ctg combinations. Probably something like this would work:

by(df, paste(df$clss, df$ctg), mapply(abline, ... ))

But I could not figure out how.

Upvotes: 1

Views: 724

Answers (2)

jlhoward
jlhoward

Reputation: 59385

Using ggplot:

library(ggplot2)
gg       <- df
gg$color <- paste(gg$clss,".",gg$ctg,sep="")
ggplot(gg) +
  geom_point(aes(x=-10,y=-10,color=color)) +   # need this to display a legend...
  geom_abline(aes(slope=slope, intercept=intercept, color=color)) +
  xlim(0,10) + ylim(0,10) + labs(x="X",y="Y")

Produces this:

Upvotes: 1

user1317221_G
user1317221_G

Reputation: 15461

It turns out in your case you only have 4 unique clss and ctg combinations, so I just picked some random colours and modified your mapply

# get colour for each combination
x <- sample(colours(), length(unique(paste0(df$clss, df$ctg)))) 
# how many of each combination are there
q <-  aggregate(df$intercept, by=list(paste0(df$clss, df$ctg)), length)
# make a colour vector
mycols <- rep(x, q[,2])


mapply(function(x,y,z) { abline(x, y, col=z) }, 
       df$intercept, df$slope, 
       as.list(mycols) )

#You could obviously pick the colours yourself or choose a gradient

Upvotes: 1

Related Questions