本文介绍了尽管aes_string在R中,ggplot在函数中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有以下数据和代码,但函数不起作用: 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 = name(ddf)[1]),stat =identity)+ geom_text(aes_string(x = 1,y = cumsum(names(ddf)[2]),label = names(ddf)[2 ]))} myplot(df1) 错误:提供给连续比例的离散值另外:警告消息: lapply(x,f):通过强制引入NAs 我尝试了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])) 解决方案您正尝试在脚本的第三行中对名称应用累积求和。这应该工作: pre $ my $ g $ 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]))} I have following data and code but the function is not working:df1 firstvar secondvar1 a1 252 a2 503 a3 75df1 = 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 scaleIn addition: Warning message:In lapply(x, f) : NAs introduced by coercionI 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])) 解决方案 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]))} 这篇关于尽管aes_string在R中,ggplot在函数中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
06-05 20:54