我正在尝试在R中执行我的第一个函数。我有一个inderminate列的数据框,我想创建每组列的ggplot。例如,列,1& 2,1& 3,1& 4等。
然而,当我尝试以下函数时,我得到了找不到对象的错误,但只有当我们得到ggplot部分时才会这样。
谢谢,
BrandPlot=function(Brand){
NoCol=ncol(Brand)
count=2
while (count<=NoCol){
return(ggplot(Brand, aes(x=Brand[,1], y=Brand[,count]))+geom_point())
count=(count+1)
}
}
澄清,
我正在尝试获得效果(另外,我计划添加更多其他内容,例如geom_smooth()但我想先让它工作
ggplot(Brand, aes(x=Brand[,1], y=Brand[,2]))+geom_point
ggplot(Brand, aes(x=Brand[,1], y=Brand[,3]))+geom_point
ggplot(Brand, aes(x=Brand[,1], y=Brand[,4]))+geom_point
ggplot(Brand, aes(x=Brand[,1], y=Brand[,5]))+geom_point
(另外,我计划添加geom_smooth()之类的其他内容)但是我想先让它工作
答案 0 :(得分:1)
根据上面的说明,这样的事情可能就是你要找的......
brandplot <- function(x){
require(reshape2)
require(ggplot2)
x_melt <- melt(x, id.vars = names(x)[1])
ggplot(x_melt,
aes_string(x = names(x_melt)[1],
y = 'value',
group = 'variable')) +
geom_point() +
facet_wrap( ~ variable)
}
dat <- data.frame(a = sample(1:10, 25, T),
b = sample(20:30, 25, T),
c = sample(40:50, 25, T))
brandplot(dat)
答案 1 :(得分:1)
[注意:@ maloneypatr的解决方案是为您的应用程序使用ggplot
的更好方法]。
直接回答你的问题,有几个问题。
count=2
),所以你永远不会从中获得多个图。ggplot
在aes(...)
中定义的数据框的上下文中评估data=...
的参数,因此它正在查找Brand$Brand
之类的内容(例如,数据框Brand
中名为Brand
的列)。由于没有此类列,因此您会收到 Object not found 错误。以下代码将生成一系列n-1
图,其中n = ncol(Brand)
。
BrandPlot=function(Brand){
for (count in 2:ncol(Brand)){
ggp <- ggplot(Brand, aes_string(x=names(Brand)[1], y=names(Brand)[count]))
ggp <- ggp + geom_point()
ggp <- ggp + ggtitle(paste(names(Brand)[count], " vs. ", names(Brand)[1]))
plot(ggp)
}
}