2

I want to make a plot that looks like this in ggplot2:

enter image description here

Here's a dummy dataset:

set.seed(1)
dat <- data.frame(x = exp(rnorm(6)),
                  f1 = factor(c("a","b","c","c","d","d")),
                  f2 = factor(c("","","1","2","1","2")))

And a non-working example:

ggplot(data=dat, aes(x=f1, y=x, fill= f2)) +
  geom_bar(stat="identity", width=0.9)+
  scale_fill_manual(values=c("red", "blue", rep("green",4)))

enter image description here

I could do this by brute force in base graphics, but I'm unsure how to go about it in ggplot2, and I need to use ggplot2 so as to keep this plot consistent with the theme I'm using throughout the project.

So how do I make the factors 1 and 2 go side by side? And how do I center the labels like I have in the drawing? And how do I make the colors behave?

generic_user
  • 3,430
  • 3
  • 32
  • 56
  • You may be looking for `position_dodge` instead of the default stacking. For multiple centered labels see [my answer here](https://stackoverflow.com/a/36337286/2461552). Other answers to that question may be useful, as well. – aosmith Dec 05 '17 at 21:33

1 Answers1

0

You are trying to make a barplot with grouped bars, a question that was answered here: Grouped bar plot in ggplot

fill only determines the colors, not the grouping, this is why you get blue and green bars for c and d.

Nakx
  • 1,460
  • 1
  • 23
  • 32