ggplot2(有序条形图)的函数:eval(expr,envir,enclos)中的错误:找不到对象

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

我在 R 中遇到有关环境的错误,但我不知道如何解决。我想创建一个使用 ggplot2 绘制有序条形图的函数。有序意味着计数最高的特征将绘制在位置 1 上,计数最少的特征将绘制在最后一个位置(降序)。

这是我的功能:

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)
}

我得到的错误是 Error in eval(expr, envir, enclos) : object 'rn' not found。 尝试

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

函数中的注释行对因子重新排序(这在末尾给出了有序的条形图),它给出了相同的结果(当 .GlobalEnv 中的 运行 与其上面的两行一样) .

运行 函数外的函数体给出了有序的条形图,但是如果 rndf.GlobalEnv 中删除,则会引发错误。

你知道怎么解决吗?

你可以稍微修改一下你的函数:

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)