我想创建一个函数,将标签添加到现有的图(内置于ggplot2中),并根据数据的X和Y值的比例定位标签。但是,当我在函数中创建变量h和v时,它们在函数外部无法识别。有办法解决这个问题吗?
alphabet = data.frame("X"=c(1,2,3), "Y"=c(1,2,3), "Label"=c("A", "B", "C"))
plot = ggplot(data = alphabet, aes(x = X, y = Y)) + geom_point()
addLabel = function(d, p, row) {
h = max(d$X)*0.5
v = max(d$Y)*0.5
p = p + geom_text(data=d[row,], aes(x = X+h, y = Y+v, label = Label))
return(p)
}
addLabel(alphabet, plot, 1)
### Returns:
Error in eval(expr, envir, enclos) : object 'h' not found
答案 0 :(得分:1)
ggplot
将始终最有效。类似的东西:
addLabel = function(d, p, row) {
row_d = d[row, ]
row_d$h = max(row_d$X)*0.5
row_d$v = max(row_d$Y)*0.5
p = p + geom_text(data=row_d, aes(x = X+h, y = Y+v, label = Label))
return(p)
}
addLabel(alphabet, plot, 1)