tegulia 比如我要写一个函数,这个函数调用ggplot进行画直方图: 函数有两个参数,一个是数据框,一个是要画的这个列名 histogram<-function(df,lie){ ggplot(df)+geom_histogram(aes(x=cyl),fill="#880011") } 这时histogram(data=mtcars)可以画图,但是怎么把列名传递给函数内部的geom_histogram(aes(x=cyl))呢? 比如,如果函数改为 ggplot(df)+geom_histogram(aes(x=lie),fill="#880011"),如何传递列名? 例如 histogram(data=mtcars,lie='cyl'),这种情况传递了‘cyl’这个字符,传递不了cyl列。 histogram(data=mtcars,lie=cyl),这种情况会报错:错误于eval(expr, envir, enclos) : 找不到对象'lie' 谢谢! 附录: > head(mtcars) mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
tegulia 知道问题的原因了,见: http://tegulia.com/2015/03/04/ggplot%E8%87%AA%E6%9E%84%E5%BB%BA%E5%87%BD%E6%95%B0%E9%9C%80%E8%A6%81%E6%B3%A8%E6%84%8F%E7%9A%84%E4%B8%89%E4%B8%AA%E9%97%AE%E9%A2%98.html
libingfei 柱形图,你可以试下下面的语句,定制x,y。 可以先统计后绘制,这样比较灵活 ggplot(data=mtcars)+geom_histogram(stat="identity",aes(x=rownames(data),y=cyl),fill="#880011")
tegulia [未知用户] 问题是没法在自定义函数histogram()中,传递cyl这个列名啊。 histogram(data=mtcars,lie=’cyl’),这种情况传递了‘cyl’这个字符,传递不了cyl列。 histogram(data=mtcars,lie=cyl),这种情况会报错:错误于eval(expr, envir, enclos) : 找不到对象’lie’