1

Similar questions have been asked before (e.g., one; two), however, the answers seem to be missing the point; also, my question is slightly different. Here is the base plot:

enter image description here

And this is the code that created it:

p1 <- ggplot(data=a2.st, aes(x=Type, y=lFreq, fill=factor(Hit))) +
    geom_bar(position='stack', stat='identity', width=0.5) +
    scale_x_discrete(name='Type',
        breaks=breaks, labels=labels) +
    scale_y_continuous('Frequency', limits=c(0, 240)) +
    scale_fill_manual(values=c('#d95f02','#1b9e77'), name='Hit:',
        breaks=c('0','1'),
        labels=c('yes','no')) +
    theme(plot.title=element_text(hjust=0.5),
        axis.text.x=element_text(size=10, angle=45, vjust=1, hjust=1),
        axis.text.y=element_text(size=11),
        axis.title=element_text(size=12),
        legend.text=element_text(size=10))
p1

Instead of one stacked bar for a level of Type, is there a way to add three more bars such that Type differentiates between four levels of another variable? In other words, each Type would group four levels of variable Level.

2 Answers 2

1

You can try using interaction() to specify the fill (e.g. fill = interaction(Type, Level)) or create it as a separate variable beforehand, if its easier, and then specify a scale_fill_manual to make sure you get the colors right.

In my experience, the hard part is producing a legend that is not horrible. The best strategy I've found is the one used to make bivariate choropleths, but it is a lot of work, and might be overkill for your needs.

Sign up to request clarification or add additional context in comments.

Comments

0

After some exploration, it seems more efficient to use a mosaic plot utilising the power of ggmosaic package, for example:

require(ggmosaic)

newdf = olddf[rep(1:nrow(olddf), olddf$Freq),]
mosaic1 <- ggplot(data=newdf) +
  geom_mosaic(aes(x=product(Hit, Type, Level), fill=Hit)) +
  theme(axis.text.x=element_text(angle=90, hjust=1, vjust=0.5)) + 
  labs(y='Y', x='X', title='TITLE')
mosaic1

Fantastic resource can be found here: Generalized Mosaic Plots in the ggplot2 Framework

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.