tnaake
tnaake

Reputation: 489

Function with ggplot2 (ordered barplot): Error in eval(expr, envir, enclos): object not found

I got an error concerning environments in R but I don't know how to solve it. I would like to create a function which plots an ordered barplot using ggplot2. Ordered means that the feature with highest count will be plotted on position 1 and the feature with least counts will be at the last position (decreasing order).

This is my function:

plotBarPlot <- function(result) {

    result <- table(result)
    result <- sort(result)
    df <- data.frame(num = result)
    rn <- rownames(df)
    rn <- factor(rn, levels = rn)
    gg <- ggplot(data = df, aes(rn, df$num))
    ##gg <- ggplot(data = df, aes(reorder(rownames(df), df$num), df$num))
    gg <- gg + geom_bar(stat = "identity")
    gg <- gg + ylab("counts") + xlab("")
    gg <- gg + coord_flip()
    return(gg)
}

The error I get is Error in eval(expr, envir, enclos) : object 'rn' not found. Try

result <- c(rep("red", 3), rep("blue", 5), rep("green", 10), rep("yellow", 2))
plotBarPlot(result)

The commented line in the function reorders the factors (this gives the ordered barplot at the end), it gives the same result (when running in .GlobalEnv as the two lines above it).

Running the body of the function outside of the function gives the ordered barplot, but if rn and df is removed from .GlobalEnv the error is raised.

Do you know how to solve it?

Upvotes: 0

Views: 361

Answers (1)

user3710546
user3710546

Reputation:

You can slightly modify your function:

plotBarPlot <- function(result) {
    df <- as.data.frame(table(result))
    df <- df[with(df, order(Freq)),]
    df$result <- with(df, factor(result, levels = result))
    gg <- ggplot(data = df, aes(result, Freq)) +
          geom_bar(stat = "identity") + 
          ylab("counts") + 
          xlab("") + 
          coord_flip()
    print(gg)
}

result <- c(rep("red", 3), rep("blue", 5), rep("green", 10), rep("yellow", 2))
plotBarPlot(result)

enter image description here

Upvotes: 1

Related Questions