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

如何在R语言中为sig curve曲线图添加仅触达曲线的水平线?

解决ggplot中S型曲线添加仅触达曲线的水平线问题

问题分析

geom_hline会绘制贯穿整个绘图区域的水平线,无法实现仅触达曲线的效果。要达到需求,需要用geom_segment指定线段的起始与结束位置,精准控制水平线的长度。

核心思路

利用你已有的df数据(其中Points是S型曲线上对应X值的x坐标),为每个X值创建一条从绘图区域边缘到曲线上对应点的水平线段,而非全宽水平线。

完整代码

library(ggplot2)

df<-data.frame(Points=c(-5.5,-1,-.5,0,.5,1,1.5,2,5.5),X=c(.002,.1,.15,.17,.18,.2,.25,.3,.7))

df2<-data.frame(Points=seq(-10,10,by=.1),X=c(0.01,  0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.01,   0.02,   0.02,   0.02,   0.02,   0.02,   0.02,   0.02,   0.02,   0.02,   0.02,   0.02,   0.02,   0.02,   0.02,   0.02,   0.02,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.04,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.05,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.06,   0.07,   0.07,   0.07,   0.07,   0.07,   0.08,   0.08,   0.08,   0.08,   0.09,   0.09,   0.09,   0.09,   0.1,    0.1,    0.1,    0.1,    0.11,   0.11,   0.11,   0.12,   0.12,   0.12,   0.13,   0.13,   0.15,   0.15,   0.15,   0.16,   0.16,   0.17,   0.17,   0.18,   0.18,   0.19,   0.19,   0.2,    0.2,    0.21,   0.22,   0.22,   0.22,   0.23,   0.23,   0.24,   0.25,   0.25,   0.26,   0.27,   0.28,   0.29,   0.3,    0.3,    0.31,   0.31,   0.32,   0.33,   0.34,   0.36,   0.36,   0.37,   0.38,   0.39,   0.39,   0.41,   0.42,   0.42,   0.44,   0.45,   0.46,   0.47,   0.48,   0.49,   0.5,    0.51,   0.52,   0.54,   0.55,   0.56,   0.57,   0.58,   0.59,   0.6,    0.61,   0.62,   0.64,   0.65,   0.66,   0.67,   0.68,   0.69,   0.7,    0.71,   0.73,   0.74,   0.75,   0.76,   0.77,   0.78,   0.79,   0.8,    0.81,   0.82,   0.83,   0.83,   0.84,   0.85,   0.86,   0.87,   0.88,   0.88,   0.89,   0.9,    0.9,    0.91,   0.92,   0.92,   0.93,   0.93,   0.94,   0.94,   0.95,   0.95,   0.96,   0.96,   0.96,   0.97,   0.97,   0.97))

# 获取x轴的最小和最大值
x_min <- min(df2$Points)
x_max <- max(df2$Points)

ggplot(df2,aes(x=Points,y=X))+
  geom_line()+
  # 绘制从左边缘到曲线上对应点的水平线
  geom_segment(data = df, 
               aes(x = x_min, xend = Points, y = X, yend = X),
               color = "red")

代码说明

  • geom_segment通过指定x(起点x坐标)、xend(终点x坐标)、y和yend(保持一致的y坐标)来绘制精准长度的线段。
  • 如果需要水平线从曲线延伸到右边缘,只需将aes中的x = x_min改为x = Points,xend = Points改为xend = x_max即可。

内容的提问来源于stack exchange,提问作者a_js12

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:25:03