Search code examples
rggplot2scalefacetfacet-wrap

Set explicit order of variables in facet warp + ggplot + r


I have a dataset that I am grouping for the purpose of breaking into separate facets.

This works well though I am running into an issue where the variables are being sorted in alphabetical order instead of the order they are in in the dataframe.

In a regular plot I would just need to specify the list of names and set the order with scale_x_discrete, though when I try this with the facet_wrap it's giving me the error:

Error in seq_len(n) : argument must be coercible to non-negative integer
In addition: Warning messages:
1: Removed 8 rows containing missing values (position_stack). 
2: In max(f) : no non-missing arguments to max; returning -Inf

In the examples below I've included it with and without scale_x_discrete.

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)

mdtype$group = ifelse(mdtype$Name %in% c("Jim", "Bob"),
                      "Group1", "Group2")

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 + facet_wrap(~group) #+ scale_x_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)

mdtype$group = ifelse(mdtype$Name %in% c("Jim", "Bob"),
                      "Group1", "Group2")

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 + facet_wrap(~group) + scale_x_discrete(limits = names)

The order I'm trying to achieve is "Jim","Bob" on the left and "Sue","Sally" on the right.


Solution

  • insted of scale_x_discrete use scale_fill_discrete(limits = names)