我有一个图表,我想在图表上叠加一个功能表格.看起来很直接,但我错过了一些东西.这是我stat_function用来尝试添加f1到图表的示例数据和插图:
library(ggplot2)
sample_data <- data.frame(rate = c(0.514492753623188, 0.553072625698324, 0.656527249683143, 0.675694939415538,
0.68681076312307, 0.715657311669128, 0.792349726775956),
level = c(0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85) )
f1 <- function(x) pbeta(x, shape1=1.01, shape2=.9 ) * 100
g <- ggplot() +
geom_line(aes(y = rate*100 , x = level),
data = sample_data, stat="identity") +
stat_function(fun = f1)
g
Run Code Online (Sandbox Code Playgroud)

如你所见,f1线路不在那里.
因此,作为替代方案,我可以将点添加到初始data.frame,然后使用geom_line以下示例说明:
## add f1 to data.frame
sample_data$f1 <- f1(sample_data$level )
g <- ggplot() +
geom_line(aes(y = rate*100 , x = level),
data = sample_data, stat="identity") +
geom_line(aes(y = f1 , x = level),
data = sample_data, stat="identity", color='red')
g
Run Code Online (Sandbox Code Playgroud)

这样stat_function可行,并得到我需要的东西,但我无法弄清楚为什么不起作用.有小费吗?
您需要data = sample_data, aes(y = rate*100 , x = level)在第一次ggplot通话时stat_function知道正在使用的数据
library(ggplot2)
sample_data <- data.frame(rate = c(0.514492753623188, 0.553072625698324, 0.656527249683143, 0.675694939415538,
0.68681076312307, 0.715657311669128, 0.792349726775956),
level = c(0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85) )
f1 <- function(x) pbeta(x, shape1=1.01, shape2=.9 ) * 100
g <- ggplot(data = sample_data, aes(y = rate*100 , x = level)) +
geom_line() +
stat_function(fun = f1, color = "red")
g
Run Code Online (Sandbox Code Playgroud)

由reprex包创建于2018-05-20 (v0.2.0).