How can I have different color for each bar of stack barplots? in R -
my question maybe simple couldn't find answer! have matrix 12 entries , made stack barplot barplot function in r. code:
mydata <- matrix(nrow=2,ncol=6, rbind(sample(1:12, replace=t))) barplot(mydata, xlim=c(0,25),horiz=t, legend.text = c("a","b","c","d","e","f"), col=c("blue","green"),axisnames = t, main="stack barplot")
here image code:
what want give each of group (a:f , blue part) different color couldn't add more 2 color.
and know how can start plot x=2 instead of 0. know it's possible choose range of x using xlim=c(2,25) when choose part of bars out of range , picture this:
what want ignore part of bars smaller 2 , start x-axis 2 , show rest of bars instead of put them out of range.
thank in advance,
i'm not entirely sure if you're looking for: 'a' has 2 values (x1 , x2), legend seems hint otherwise.
here way approach want ggplot. first set data.frame (required ggplot):
set.seed(1) df <- data.frame( name = letters[1:6], x1=sample(1:6, replace=t), x2=sample(1:6, replace=t)) name x1 x2 1 5 3 2 b 3 5 3 c 5 6 4 d 3 2 5 e 5 4 6 f 6 1
next, ggplot requires in long format:
# make ggplot format require(dplyr); require(reshape2) df <- df %>% melt(id.vars="name") name variable value 1 x1 5 2 b x1 3 3 c x1 5 4 d x1 3 5 e x1 5 6 f x1 6 ...
now, want bars different colour, need give them alternate name can assign colour manually.
df <- df %>% mutate(variable=ifelse( name %in% c("b", "d", "f") & variable == "x1", "highlight_x1", as.character(variable))) name variable value 1 x1 2 2 b highlight_x1 3 3 c x1 4 4 d highlight_x1 6 5 e x1 2 6 f highlight_x1 6 7 x2 6 8 b x2 4 ...
next, build plot. uses standard colours:
require(ggplot2) p <- ggplot(data=df, aes(y=value, x=name, fill=factor(variable))) + geom_bar(stat="identity", colour="black") + theme_bw() + coord_flip(ylim=c(1,10)) # zooms in on y = c(2,12)
note use coord_flip (which in turn calls coord_cartesian) ylim=c(1,10) parameter 'zoom in' on data. doesn't remove data, ignores (unlike setting limits in scale). now, if manually specify colours:
p + scale_fill_manual(values = c( "x1"="coral3", "x2"="chartreuse3", "highlight_x1"="cornflowerblue"))
Comments
Post a Comment