Search code examples
rggplot2plotbar-chartstacked-chart

Explicitly Set Order of "fill" Variables in Stacked Bar + ggplot


I'm trying to explicitly set the order of the fill variables in a stacked bar chart.

To do so I'm using the scale_y_discrete variable and setting the limits to a predetermined list I'm making, in the case of the example names.

This works perfect when ordering the x axis but when I take the same approach for the y it's not having any effect and is causing an issues with the axis labels.

The below examples are the chart with and without the attempted ordering.

Without:

library(ggplot2)
library(reshape2)

df_dtype <- data.frame(Name = c("Jim","Bob","Sue","Sally"),
                       Pre = c(150, 200, 325, 120),
                       Post = c(70,120,200,100) )

mdtype <- melt(df_dtype)

names = c("Jim","Bob","Sue","Sally")
p <- ggplot(mdtype, aes(x=variable, y=value, fill=Name)) + 
  geom_bar(position="stack", stat="identity") + 
  ylab("Frequency") + xlab("") + ggtitle("Report Type") +
  theme(axis.ticks.x = element_blank(),axis.text.x = element_text(angle = 45, vjust = 1, hjust=1)) 
p # + scale_y_discrete(limits = names)

With:

library(ggplot2)
library(reshape2)

df_dtype <- data.frame(Name = c("Jim","Bob","Sue","Sally"),
                       Pre = c(150, 200, 325, 120),
                       Post = c(70,120,200,100) )

mdtype <- melt(df_dtype)

names = c("Jim","Bob","Sue","Sally")
p <- ggplot(mdtype, aes(x=variable, y=value, fill=Name)) + 
  geom_bar(position="stack", stat="identity") + 
  ylab("Frequency") + xlab("") + ggtitle("Report Type") +
  theme(axis.ticks.x = element_blank(),axis.text.x = element_text(angle = 45, vjust = 1, hjust=1)) 
p # + scale_y_discrete(limits = names)

I'm trying to set it so the order of the piecs in the stack are arranged in the order of this list names = c("Jim","Bob","Sue","Sally")


Solution

  • Make the fill variable a factor with the correct variable ordering as defined by names

    ggplot(mdtype, aes(variable, value, fill = factor(Name, names))) + 
      geom_col(position = "stack") + 
      labs(x = NULL, y = "Frequency", title = "Report Type", fill = "Name") +
      theme(axis.ticks.x = element_blank(),
            axis.text.x  = element_text(angle = 45, vjust = 1, hjust = 1)) 
    

    enter image description here