Search code examples
rggplot2geom-text

Object not found even though it is globally declared when using geom_text()


R complains about a variable not existing even though it's been declared globally. Here's a snippet of code that reproduces the problem:

dataSet2 <- data.frame(FR=c("N", "S", "S","S"))
totalTrx <- 2000
# Errors
ggplot(dataSet2, aes(FR)) +
    geom_bar(aes(y = prop.table(..count..) * 100, fill=FR)) +
    geom_text(aes(y = prop.table(..count..) * 100 + 2,label = paste0('(', prop.table(..count..)*totalTrx, ')')), stat='count')

# Runs
ggplot(dataSet2, aes(FR)) +
    geom_bar(aes(y = prop.table(..count..) * 100, fill=FR)) +
    geom_text(aes(y = prop.table(..count..) * 100 + 2,label = paste0('(', prop.table(..count..)*100, ')')), stat='count')

# Also runs
ggplot(dataSet2, aes(FR)) +
        geom_bar(aes(y = prop.table(..count..) * 100, fill=FR)) +
        geom_text(aes(y = prop.table(..count..) * 100 + 2,label = paste0('(', totalTrx, ')')), stat='count')

Any idea of what's going on here? Using prop.table and using a global variable seem mutually exclusive.


Solution

  • This issue is related to ggplot, not to prop.table if you define "totalTrx" inside "aes" it is solved.

    ggplot(dataSet2, aes(FR)) +
      geom_bar(aes(y = prop.table(..count..) * 100, fill=FR)) +
      geom_text(aes(y = prop.table(..count..) * 100 + 2,label = paste0('(', prop.table(..count..)*totalTrx, ')'), totalTrx = totalTrx), stat='count')