尽管在R中有aes_string,但函数中的ggplot无法正常工作

时间:2014-09-11 04:12:21

标签: r ggplot2

我有以下数据和代码,但功能不起作用:

df1
  firstvar secondvar
1       a1        25
2       a2        50
3       a3        75


df1 = structure(list(firstvar = c("a1", "a2", "a3"), secondvar = c(25L, 
50L, 75L)), .Names = c("firstvar", "secondvar"), class = "data.frame", row.names = c(NA, 
-3L))

myplot = function(ddf){ 
    ggplot(ddf) +
        geom_bar(aes_string(1, names(ddf)[2], fill=names(ddf)[1]), stat="identity")+
        geom_text(aes_string(x=1, y=cumsum(names(ddf)[2]), label=names(ddf)[2]))
}

myplot(df1)

Error: Discrete value supplied to continuous scale
In addition: Warning message:
In lapply(x, f) : NAs introduced by coercion

我尝试了scale_x_discrete()等,但它没有帮助。如何更正此错误?

编辑: 功能不足,以下代码运行良好:

ggplot() +
  geom_bar(aes(x=1, y=ddf[,2], fill=ddf[,1]), stat="identity")+
  geom_text(aes(x=1, y=cumsum(ddf[,2]), label=ddf[,2]))

1 个答案:

答案 0 :(得分:0)

您正尝试对脚本第三行中的名称应用累积求和。这应该有效:

myplot = function(ddf){ 
    ggplot(ddf) +
        geom_bar(aes_string(1, names(ddf)[2], fill=names(ddf)[1]), stat="identity")+
        geom_text(aes_string(x=1, y=cumsum((ddf)[2]), label=names(ddf)[2]))
}