Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add a third variable to graph with geom_rug?

Tags:

r

ggplot2

I have sports dataset which shows a team's result, win draw or loss, cumulative games played and league standing. A simple plot of position by games played is produced thus

df<- data.frame(played=c(1:5), 
        result=c("W","L","D","D","L"), 
        position=c(1,3,4,4,5))
ggplot() + 
     geom_line(data=df,aes(x=played,y=position)) + 
     scale_y_reverse()

I would like to add a rug on the x axis with a different colour for each result, say W is green, L red and D, blue but cannot seem to solve it using geom_rug or adding a geom_bar.

like image 382
pssguy Avatar asked Oct 19 '25 02:10

pssguy


1 Answers

This should do the trick:

##The data frame df is now inherited by
##the other geom's
ggplot(data=df,aes(x=played,y=position)) + 
  geom_line() +
  scale_y_reverse() +
  geom_rug(sides="b", aes(colour=result))

In the geom_rug function, we specify that we only want a rug on the bottom and that we should colour the lines conditional on the result. To change the colours, look at the scale_colour_* functions. For your particular colours, try:

+ scale_colour_manual(values=c("blue","red", "green"))

enter image description here

like image 128
csgillespie Avatar answered Oct 20 '25 18:10

csgillespie