R ecdf折线图上的高亮点
R Highlight point on ecdf line graph
我正在使用 ggplot 和 stat_ecdf 函数创建频率图。我想将 Y 值添加到特定 X 值的图表中,但不知道如何做。 geom_point 或 geom_text 似乎是可能的选项,但由于 stat_ecdf 自动计算 Y,我不知道如何在 geom_point/text 映射中调用该值。
我的初始情节的示例代码是:
x = as.data.frame(rnorm(100))
ggplot(x, aes(x)) +
stat_ecdf()
现在我该如何在此处添加特定的 y-x 点,例如x = -1 处的 y 值。
最简单的方法是使用 stats
包中的 ecdf()
预先创建 ecdf 函数,然后使用 geom_label()
.
绘制它
library(ggplot2)
# create a data.frame with column name
x = data.frame(col1 = rnorm(100))
# create ecdf function
e = ecdf(x$col1)
# plot the result
ggplot(x, aes(col1)) +
stat_ecdf() +
geom_label(aes(x = -1, y = e(-1)),
label = e(-1))
你可以试试
library(tidyverse)
# data
set.seed(123)
df = data.frame(x=rnorm(100))
# Plot
Values <- c(-1,0.5,2)
df %>%
mutate(gr=FALSE) %>%
bind_rows(data.frame(x=Values,gr=TRUE)) %>%
mutate(y=ecdf(x)(x)) %>%
mutate(xmin=min(x)) %>%
ggplot(aes(x, y)) +
stat_ecdf() +
geom_point(data=. %>% filter(gr), aes(x, y)) +
geom_segment(data=. %>% filter(gr),aes(y=y,x=xmin, xend=x,yend=y), color="red")+
geom_segment(data=. %>% filter(gr),aes(y=0,x=x, xend=x,yend=y), color="red") +
ggrepel::geom_label_repel(data=. %>% filter(gr),
aes(x, y, label=paste("x=",round(x,2),"\ny=",round(y,2))))
想法是在开头添加 y
值,连同索引 gr
指定要显示的 Values
。
编辑:
由于此代码将点添加到实际数据中,这对于曲线来说可能是错误的,因此至少应考虑在 ecdf 函数中删除这些点 stat_ecdf(data=. %>% filter(!gr))
我正在使用 ggplot 和 stat_ecdf 函数创建频率图。我想将 Y 值添加到特定 X 值的图表中,但不知道如何做。 geom_point 或 geom_text 似乎是可能的选项,但由于 stat_ecdf 自动计算 Y,我不知道如何在 geom_point/text 映射中调用该值。
我的初始情节的示例代码是:
x = as.data.frame(rnorm(100))
ggplot(x, aes(x)) +
stat_ecdf()
现在我该如何在此处添加特定的 y-x 点,例如x = -1 处的 y 值。
最简单的方法是使用 stats
包中的 ecdf()
预先创建 ecdf 函数,然后使用 geom_label()
.
library(ggplot2)
# create a data.frame with column name
x = data.frame(col1 = rnorm(100))
# create ecdf function
e = ecdf(x$col1)
# plot the result
ggplot(x, aes(col1)) +
stat_ecdf() +
geom_label(aes(x = -1, y = e(-1)),
label = e(-1))
你可以试试
library(tidyverse)
# data
set.seed(123)
df = data.frame(x=rnorm(100))
# Plot
Values <- c(-1,0.5,2)
df %>%
mutate(gr=FALSE) %>%
bind_rows(data.frame(x=Values,gr=TRUE)) %>%
mutate(y=ecdf(x)(x)) %>%
mutate(xmin=min(x)) %>%
ggplot(aes(x, y)) +
stat_ecdf() +
geom_point(data=. %>% filter(gr), aes(x, y)) +
geom_segment(data=. %>% filter(gr),aes(y=y,x=xmin, xend=x,yend=y), color="red")+
geom_segment(data=. %>% filter(gr),aes(y=0,x=x, xend=x,yend=y), color="red") +
ggrepel::geom_label_repel(data=. %>% filter(gr),
aes(x, y, label=paste("x=",round(x,2),"\ny=",round(y,2))))
想法是在开头添加 y
值,连同索引 gr
指定要显示的 Values
。
编辑:
由于此代码将点添加到实际数据中,这对于曲线来说可能是错误的,因此至少应考虑在 ecdf 函数中删除这些点 stat_ecdf(data=. %>% filter(!gr))