ggplot in function not working despite aes_string

2019-08-27 15:48发布

I have following data and code but the function is not working:

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

I tried scale_x_discrete() etc but it did not help. How can I correct this error?

Edit: Out of function, following code works well:

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

标签: r ggplot2
1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-27 16:10

You are trying to apply a cumulative summation on names in the third line of your script. This should work:

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]))
}
查看更多
登录 后发表回答