我在使用ggplot完成的图形的右侧添加第二个垂直轴的函数存在问题,将比例因子应用于所表示的变量。
图形和功能的代码如下:
#Libraries
library(ggplot2)
#Data
df <- data.frame(
equis = c(1,1,2,2,3,3,4,4,5,5,6,6),
ygrega = c(80,75,85,80,81,70,82,73,83,72,82,75),
zeta = c(30,30,30,30,20,20,30,30,20,20,30,30),
tip= c("inrix","det","inrix","det","inrix","det","inrix","det","inrix","det","inrix","det")
)
#Graphic
grafTest <- ggplot(data= df, aes(x= equis)) +
geom_line(aes(y= ygrega, col= tip), alpha= 0.6) +
geom_point(aes(y= ygrega, col= tip), size= 0.6, alpha= 0.6)
#Function
afeSecAxi <- function(graf, var, facMul, namAxi, type){
if(type=="line"){
graf <- graf + geom_line(aes(y=var*facMul)) +
scale_y_continuous(sec.axis = sec_axis( ~ . /facMul, name = paste(namAxi)))
return(graf)
}else if(type=="point"){
graf <- graf + geom_point(aes(y=var*facMul, colour= paste(namAxi))) +
scale_y_continuous(sec.axis = sec_axis( ~ . /facMul, name = paste(namAxi)))
return(graf)
}else{
stop("Not valid type of graphic ")
}
}
#Function example
afeSecAxi(graf = grafTest, var = df$zeta, facMul = 2.5, namAxi = "zeta", type = "line")
运行代码时,出现以下错误:
Error in FUN(X[[i]], ...) : object 'facMul' not found
我不知道为什么会出现此错误,因为如果我在函数外运行相同的代码,则图形显示正确,如下所示:
#Libraries
library(ggplot2)
#Data
df <- data.frame(
equis = c(1,1,2,2,3,3,4,4,5,5,6,6),
ygrega = c(80,75,85,80,81,70,82,73,83,72,82,75),
zeta = c(30,30,30,30,20,20,30,30,20,20,30,30),
tip= c("inrix","det","inrix","det","inrix","det","inrix","det","inrix","det","inrix","det")
)
#Graphic
grafTest <- ggplot(data= df, aes(x= equis)) +
geom_line(aes(y= ygrega, col= tip), alpha= 0.6) +
geom_point(aes(y= ygrega, col= tip), size= 0.6, alpha= 0.6)
graf = grafTest
var = df$zeta
facMul = 2.5
namAxi = "zeta"
type = "line"
graf <- graf + geom_line(aes(y=var*facMul)) +
scale_y_continuous(sec.axis = sec_axis( ~ . /facMul, name = paste(namAxi)))
plot(graf)
有人知道为什么会出现错误吗?
下面显示的是初始图形和带有第二个轴的图形:
在此致以谢意和感谢。