R抱怨一个变量不存在,即使它已被全球宣布。这是一段代码,可以重现问题:
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')
知道这里发生了什么?使用prop.table
并使用全局变量似乎是互斥的。
答案 0 :(得分:1)
此问题与ggplot有关,而与prop.table无关 如果你定义&#34; totalTrx&#34;内部&#34; aes&#34;它解决了。
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')