r - Exclude unused factor levels in each facet in ggplot -
consider data frame:
df <- data.frame(vars=c(rnorm(3),rnorm(3,2,1), rnorm(3,1,1)), names=c("a","b","c","a","d","b","c","a","f"), groups=c(rep("x",3),rep("y",3),rep("z",3)))
i'm plotting ggplot:
ggplot(df, aes(reorder(names, vars), names)) + geom_bar(stat="identity") + theme_bw() + facet_grid(groups~., scales="free_x") + coord_flip() + ylab(null) + xlab(null)
it looks
i want following:
- each grid item should drop unused items, e.g. in "x" grid there should no "d" , "f"
- the x axis should the value of "vars" column. proportions in each grid should same, overall x scale should dropped. want proportions of bars in each grid intact
- the bars should in decreasing order in each grid (longer bars on top)
update:
edit using advice here error:
ggplot(df, aes(names,vars)) + geom_bar(stat="identity") + coord_flip() + theme_bw() + facet_wrap(~groups,nrow = 3,scales = "free_x") error in facet_render.wrap(plot$facet, panel, plot$coordinates, theme, : ggplot2 not support free scales non-cartesian coord or coord_flip. in addition: warning message: stacking not defined when ymin != 0
when remove coord_flip() works still warning , result not want.
this bit of workaround gives plot plot seems meet basic objectives. geom_bar
replaced geom_seqment
because seems closer you're plotting , avoids complications of coord_flip
. order of bars determined rank of vars
in each group
. y axis labels can't specified directly can use geom_text
place proper names
values next y axis these act labels. also, switched facet label left side seemed improve overall appearance of facet , y axis labels.
set.seed(177) df <- data.frame(vars=c(rnorm(3),rnorm(3,2,1), rnorm(3,1,1)), names=c("a","b","c","a","d","b","c","a","f"), groups=c(rep("x",3),rep("y",3),rep("z",3))) library(ggplot2) sp1 <- ggplot(data=transform(df, ranked=ave(vars, groups, fun=rank)), aes( x=vars, y=ranked)) sp1 <- sp1 + geom_segment( aes( xend = 0, yend = ranked), size=10) sp1 <- sp1 + geom_text( aes( x = min(vars), y= ranked, label = names), hjust= 4) sp1 <- sp1 + scale_y_discrete(label=null) sp1 <- sp1 + theme_bw() sp1 <- sp1 + facet_grid( groups ~ ., scales="free", switch="y") plot(sp1)
plot looks like
Comments
Post a Comment