Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I color a specific bar in a bar plot (qplot, ggplot2)

Tags:

r

ggplot2

I plotted a facet graph using qplot and I used "fill" option to color the bars based on their values(high=Red, med=violet, low=blue)

http://i.stack.imgur.com/raEzA.png

My code is:

x = qplot(as.character(exon),Divergence_from_Average, data=HRA_LR,     
  geom="histogram",fill=abs(Divergence_from_Average)) 
y = x +facet_grid(~probeset_id, scales="free_x", space= "free") + theme_bw() +     
  opts(title="GRP78/HSPA5  (HRN vs LR)") 

If I only need to color the bars which is above 0.3 and leave rest of the unfilled how can I do that?

like image 630
Jana Avatar asked Mar 18 '11 22:03

Jana


1 Answers

You can tweak this to suit your needs, but here's the basic concept:

We'll define a new binary variable that determines whether or not to fill the bars. We'll pass that into the fill argument as a factor and use scale_colour_manual to give them the colours we want. I also passed set the colour parameter to red so that you can see the white bars on the white background.

#Sample data
df <- data.frame(
    divergence = rnorm(10), 
    exons = paste("E", sample(1:20, 10, TRUE), sep = ""), 
    probset_id = sample(letters, 10, FALSE) 
)

#Binary flag for fill
df$fill <- with(df, ifelse(divergence > .3, 1,0))


ggplot(data = df, aes(as.character(exons), divergence, fill = factor(fill))) +
    geom_histogram(colour = "red", legend = FALSE) +
    scale_fill_manual(values = c("1" = "red", "0" = "white"), legend = FALSE) +
    facet_grid(~ probset_id, scales="free_x", space= "free") +
    theme_bw() + opts(title="GRP78/HSPA5  (HRN vs LR)")

Will generate something like this. I forgot to set.seed() before saving the image so your miles may vary, but consider this a proof of concept:

enter image description here

like image 54
Chase Avatar answered Oct 15 '22 05:10

Chase