R, ggplot2, facetted histogram, decending order, factor x-axis labels -
i have interesting problem need produce facetted histogram series want put in decending order each panel. below code replicates problem.
library(ggplot2) set.seed(1) ngroup = 10; nsample = 10 df <- data.frame(group=rep(1:nsample,ngroup), category = factor(sample(letters, ngroup*nsample, replace=true), levels=letters), amount = runif(ngroup*nsample)) ggplot(df,aes(x=category,y=amount)) + geom_bar(stat='identity') + facet_wrap(~group,scales='free_x') + labs(title="some random histogram facets")
which produces below output:
i have tried following:
library(ggplot2) set.seed(1) ngroup = 10; nsample = 10 df <- data.frame(group=rep(1:nsample,ngroup), category = factor(sample(letters, ngroup*nsample, replace=true), levels=letters), amount = runif(ngroup*nsample)) ggplot(df,aes(x=reorder(category,-amount),y=amount)) + geom_histogram(stat='identity') + facet_wrap(~group,scales='free_x') + labs(title="some random histogram facets")
which slight improvement (see below), no-where near should be.
any suggestions appreciated? understand x-axis labels not correspond between panels, fine application.
update: fixing labels.
mamoun's answer did job, however, of interested in fixing x-axis labels remove interaction suffixes, can done (including other desired formatting options):
library(ggplot2) set.seed(1) ngroup = 10; nsample = 10 df <- data.frame(group=factor(rep(1:nsample,ngroup)), category = factor(sample(letters, ngroup*nsample, replace=true), levels=letters), amount = runif(ngroup*nsample)) df <- ddply(df,c("group","category"),function(d){ data.frame(amount=sum(d$amount)) }) df$interaction = interaction(df$category,df$group) df$xlabel = as.character(df$category) ggplot(df,aes(x=reorder(interaction,-amount),y=amount,fill=amount)) + geom_bar(stat='identity',color="black",width=1.0) + scale_x_discrete(breaks=df$interaction,labels=df$xlabel) + facet_wrap(~group,scales='free_x') + theme_bw() + theme(legend.position=c(1,0),legend.justification=c(1,0)) + theme(axis.text.x = element_text(angle = 90, hjust = 0.5, vjust=0.5, size=6)) + scale_fill_gradient(low="blue",high="red") + labs(title="some random histogram facets",x="category")
which produces following, desired:
you can use reorder
, interaction
between groups
, category
this
ggplot(df,aes(x=reorder(interaction(category, group), -amount, sum),y=amount)) + geom_bar(stat='identity') + facet_wrap(~group,scales='free_x') + labs(title="some random histogram facets")
Comments
Post a Comment