Kumpelka
Kumpelka

Reputation: 987

R - Reorder a bar plot in a function using ggplot2

I have the following plot function using ggplot2.

Function_Plot <- function(Fun_Data, Fun_Color)
{
  MyPlot <- ggplot(data = na.omit(Fun_Data), aes_string(x = colnames(Fun_Data[2]), fill = colnames(Fun_Data[1]))) +
            geom_bar(stat = "count") +
            coord_flip() +
            scale_fill_manual(values = Fun_Color)
  return(MyPlot)
}

The result is :

Image

I need to upgrade my function to reorder the bar according frequencies of the words (in descending order). As I see the answer for another question about reordering, I try to introduce reorder function in the aes_string but it doesn't work.

A reproducible example :

a <- c("G1","G1","G1","G1","G1","G1","G1","G1","G1","G1","G2","G2","G2","G2","G2","G2","G2","G2")
b <- c("happy","sad","happy","bravery","bravery","God","sad","happy","freedom","happy","freedom",
       "God","sad","happy","freedom",NA,"money","sad")

MyData <- data.frame(Cluster = a, Word = b)
MyColor <- c("red","blue")

Function_Plot(Fun_Data = MyData, Fun_Color = MyColor)

Upvotes: 2

Views: 605

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

Well, if reordering doesn't work inside aes_string, let's try it beforehand.

Function_Plot <- function(Fun_Data, Fun_Color)
{
  Fun_Data[[2]] <- reorder(Fun_Data[[2]], Fun_Data[[2]], length)
  MyPlot <- ggplot(data = na.omit(Fun_Data), aes_string(x = colnames(Fun_Data[2]), fill = colnames(Fun_Data[1]))) +
            geom_bar(stat = "count") +
            coord_flip() +
            scale_fill_manual(values = Fun_Color)
  return(MyPlot)
}

Function_Plot()

enter image description here

Couple other notes - I'd recommend you use a more consistent style, mixing whether or not use use _ to separate words in variable names is confusing and asking for bugs.

It won't matter much unless your data is really big, but extracting names from a data frame is very efficient, whereas subsetting a data frame is less efficient. Your code subsets a data frame and then extracts the column names remaining, e.g., colnames(Fun_Data[1]). It will be cleaner to extract the names and then subset that vector: colnames(Fun_Data)[1]

Upvotes: 2

Related Questions