You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot2中stat_function无法添加至已有图表的问题求助

Why 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's rate*100 values top out at ~79.2, so ggplot automatically set the y-axis upper limit to match that. However, your f1(x) function returns a value of ~89 when x=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_function generates 100 points spanning x=0 to x=1. But your sample data only uses x values from 0.55 to 0.85. Most of the points generated for stat_function were 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:16:43