ggplot在功能上,尽管R中aes_string不工作(ggplot in function no

2019-10-29 15:28发布

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

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

Answer 1:

您正在尝试在脚本中的第三行名称适用累积求和。 这应该工作:

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


文章来源: ggplot in function not working despite aes_string in R
标签: r ggplot2