所以我正在尝试编写一个创建散点图的函数。
根据数据,我可能需要 V1 或 V2 的值来确定点的形状/颜色。 V1 中的数据仅采用特定值,V2 也是如此,但两者对于 R/ggplot 来说都是连续的,因此我将它们视为 as.factor
。我也可能回归购买 V1 或 V2。
这工作正常:
p1<-ggplot(sigmas.table,
aes(x=V4,y=V5, color=as.factor(V2),shape=as.factor(V1)))+
geom_point(size=4)+
stat_smooth(aes(group=as.factor(V2)),method=lm,formula=y~poly(x,1),size=1)
但是要将它包装在一个函数中,首先我必须切换到
aes_string
以便我可以读取列标题(我也改变了 x 轴值),但现在我无法说服 ggplot V1/V2 只取一个有限数字要分配不同点的值。 color 有点工作,但分配一个连续的阴影而不是不同的颜色,所以它也将数据视为连续的:scatter.plot<- function(s.table,x.var, col.var, shape.var, line.var){
ploti <- ggplot(s.table,
aes_string(x=x.var,y="V5", color=as.factor(col.var),shape=as.factor(shape.var)))+
geom_point(size=4)+
stat_smooth(aes_string(group=as.factor(line.var)),method=lm,formula=y~poly(x,1),size=1)+
return(ploti)}
p1 <- scatter.plot(sigmas.table,"V4","V2","V1","V2")
返回
Error: A continuous variable can not be mapped to shape
我确信有很多可用的kludges,但在我看来(也许是我的天真)就像可能有一个真正的解决方案。任何和所有的帮助表示赞赏。
附言
这是 sigmas 表的示例:
V1 V2 V3 V4 V5 V6
1: 0.3 16 0.12791584 0.3454941 0.19463432 0.04231422
2: 0.5 16 0.09908318 0.4460310 0.06286376 0.05462742
3: 0.7 16 0.08374057 0.5277510 0.03820782 0.06463604
4: 0.9 16 0.07385224 0.5984134 0.03026121 0.07329038
5: 0.3 32 0.09045016 0.2443013 0.17003319 0.02992067
6: 0.5 32 0.07006239 0.3153916 0.04250670 0.03862742
7: 0.7 32 0.05921353 0.3731763 0.02563209 0.04570458
8: 0.9 32 0.05222142 0.4231422 0.02037799 0.05182412
9: 0.3 64 0.06395792 0.1727471 0.14072683 0.02115711
10: 0.5 64 0.04954159 0.2230155 0.03286223 0.02731371
11: 0.7 64 0.04187029 0.2638755 0.01946985 0.03231802
12: 0.9 64 0.03692612 0.2992067 0.01475039 0.03664519
13: 0.3 128 0.04522508 0.1221506 0.11012266 0.01496034
14: 0.5 128 0.03503120 0.1576958 0.02260296 0.01931371
15: 0.7 128 0.02960676 0.1865882 0.01317059 0.02285229
16: 0.9 128 0.02611071 0.2115711 0.01036970 0.02591206
最佳答案
正如我在评论中所述,如果原始数据确实包含因素,则应该对其进行转换。但是,您也可以在函数中执行此操作:
scatter.plot<- function(s.table,x.var, col.var, shape.var, line.var){
s.table[,col.var] <- as.factor(s.table[,col.var])
s.table[,shape.var] <- as.factor(s.table[,shape.var])
s.table[,line.var] <- as.factor(s.table[,line.var])
ggplot(s.table, aes_string(x=x.var, y="V5", color=col.var, shape=shape.var)) +
geom_point(size=4) +
stat_smooth(aes_string(group=line.var),
method=lm, formula=y~poly(x,1), size=1)
}
关于r - ggplot2:在包装器中将连续变量传递给 "shape",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18847704/