1

Hi I have a double bar graph. I have searched for it, but I can't quite get what I want. Example of searches.

Reverse fill order of stacked bars with faceting

R - ggplot2 reverse order of bar

In ggplot2 for R, how do I reverse the order of the bar colors?

Unfortunately I dont have enough reputation to post an image :(

Here is my code:

dat9 <- data.frame(
  Response = factor(c("Yes","Yes","Yes","Yes","Yes","No", "No", "No",  "No", "No")),
  Category = factor(c("Under 45","45-64","65+","Men","Women","Under 45", "45-64", "65+", "Men", "Women"), levels=c("Under 45","45-64","65+", "Men", "Women")),
  percentage = c(79, 69, 44, 65, 72, 16, 22, 39, 25, 20))

ggplot(data=dat9, aes(x=Category, y=percentage, fill=Response,)) +
  geom_bar(stat="identity", position=position_dodge(), colour="black")

(Not enough reputation to post PNG!)

I would like to reverse the red and blue bars in the image. Also reverse the blue and red box in the legend.

Updated (Added PNG) enter image description here

Community
  • 1
  • 1
hikingpanda
  • 13
  • 1
  • 4

2 Answers2

1

You should reorder the factor levels of Response. By default, factor levels follow an alphabetical order and ggplot2 respects this ordering.

dat9 <- data.frame(
    Response = factor(c("Yes","Yes","Yes","Yes","Yes","No", "No", "No",  "No", "No")),
    Category = factor(c("Under 45","45-64","65+","Men","Women","Under 45", "45-64", "65+", "Men", "Women"), levels=c("Under 45","45-64","65+", "Men", "Women")),
    percentage = c(79, 69, 44, 65, 72, 16, 22, 39, 25, 20))
dat9$Response <- factor(dat9$Response,levels=c("Yes","No"))
ggplot(data=dat9, aes(x=Category, y=percentage, fill=Response,)) +
         geom_bar(stat="identity", position=position_dodge(), colour="black")
Adam
  • 337
  • 3
  • 10
0

You can use scale_fill_manual to pick the order and colors of the bars. This also addresses the diagonal lines through the legend key boxes.

ggplot(data=dat9, aes(x=Category, y=percentage, fill=Response,)) +
  geom_bar(stat="identity", position=position_dodge()) +
  scale_fill_manual(values = c("blue", "red"))

enter image description here

lawyeR
  • 7,488
  • 5
  • 33
  • 63