开发者

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

开发者 https://www.devze.com 2023-02-18 06:24 出处:网络
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)

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_Ave开发者_如何学Pythonrage, 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?


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:

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


Here is an example with the tips data in ggplot2

library(ggplot2)
data(tips)
qplot(day, data = tips, geom = 'blank') +  geom_bar(aes(fill = ..count.. > 65))
0

精彩评论

暂无评论...
验证码 换一张
取 消