ggplot2中stat_function无法添加至已有图表的问题求助
stat_function Didn't Show Up in Your ggplot2 Plot Hey there! Let's break down why your stat_function wasn't rendering the curve for f1, and how to get it working properly.
The Root Causes
Your stat_function was actually running, but its output was completely outside the visible area of your plot for two key reasons:
- Y-axis range was too narrow
Your sample data'srate*100values top out at ~79.2, so ggplot automatically set the y-axis upper limit to match that. However, yourf1(x)function returns a value of ~89 whenx=0.85—way above the default y-axis cap. This meant the curve was getting cut off entirely. - Mismatched X-axis range
By default,stat_functiongenerates 100 points spanningx=0tox=1. But your sample data only usesxvalues from 0.55 to 0.85. Most of the points generated forstat_functionwere outside the plot's visible x-range, and the few that were inside were already above the y-axis limit.
Fixed Code with stat_function
To fix this, we just need to align the stat_function's x-range with your data and expand the y-axis to fit the full output of 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) + # Match x-range to your sample data and set a distinct color stat_function(fun = f1, xlim = range(sample_data$level), color = "red") + # Expand y-axis to fit f1's maximum value scale_y_continuous(expand = expansion(mult = c(0, 0.1))) g
A Note on Your Alternative Approach
Just to confirm: your workaround of calculating f1 values directly into the data frame and using geom_line is totally valid! This approach is often preferred because it gives you explicit control over the points being plotted, and it's easier to debug if something goes wrong.
内容的提问来源于stack exchange,提问作者JD Long

