r - 在带有刻面的ggplot中绘制垂直线
问题描述
我有线图 y vs x。y 是 sigmoid,从 0 到 1 变化。
- 通过插值确定 y = 0.5 或非常接近的 x 的值。
- 在 x 处绘制垂直线,其中 y = 0.5
library(tidyverse)
# continuous variables
x <- seq(-5, 5, 0.1)
# compute y1
error_term <- runif(1, min = -2, max = 2)
y1 <- 1/(1 + exp(-x + error_term))
# compute y2
error_term <- runif(1, min = -2, max = 2)
y2 <- 1/(1 + exp(-x + error_term))
# merge y
y <- c(y1, y2)
x <- c(x, x)
# categorical variable
a <- c(rep(0, 101), rep(1, 101))
tbl <- tibble(x, a, y)
# TASK
# 1. determine values of x at which y = 0.5 for all categories and store them in variable x0
# 2. Use x0 to draw vertical lines in plots at x where y is 0.5
# ggplot
ggplot(data = tbl,
aes(x = x,
y = y)) +
geom_line() +
theme_bw() +
facet_grid(a ~ .)
解决方案
这确实不是 ggplot 内置的东西,因此您需要在绘图之前自己总结数据。您可以编写一个辅助函数,然后创建行所需的数据
find_intersect <- function(x,y, target=0.5) {
optimize(function(z) (approxfun(x,y)(z)-target)^2, x)$minimum
}
line_data <- tbl %>%
group_by(a) %>%
summarize(xint=find_intersect(x,y))
然后用
ggplot(data = tbl,
aes(x = x,
y = y)) +
geom_line() +
theme_bw() +
geom_vline(aes(xintercept=xint), data=line_data) +
facet_grid(a ~ .)
推荐阅读
- python - 重用客户端和服务器之间的套接字连接
- google-api - 分发依赖于 Google API InstalledAppFlow 的应用程序
- java - Java Map Reduce 使用 SequenceFIle 作为 reducer 输出
- flutter - GridView 的 shrinkWrap 不会在颤动中尽可能地缩小?
- c# - 使用文本索引的MongoDB搜索不起作用c#
- python - 如何使用 Plotly 删除堆叠和分组条形图中的 x 轴刻度标签
- php - 对 edit() VIEW 和 update() 方法重用 FormRequest authorize()
- python - 带有设置和获取方法 PAY_VAR() 错误的 Tkinter 标签
- sql - 如何生成具有开始月份日期和结束月份日期的动态表 Teradata 或 SAS SQL
- javascript - 反应原生firebase如何检查聊天室是否已经存在