在使用ggplot绘制椭圆时,是否可以将椭圆约束为实际可能的值?
例如,以下可重现的代码和数据绘制了两种物种的Ele vs. Var.Var是一个正变量,不能为负数.尽管如此,负值仍包含在结果椭圆中.是否可以在x轴上将椭圆限制为0(使用ggplot)?
更具体地说,我想象的是一个扁平边缘,椭圆体在x轴上截断为0.
library(ggplot2)
set.seed(123)
df <- data.frame(Species = rep(c("BHS", "MTG"), each = 100),
Ele = c(sample(1500:3000, 100), sample(2500:3500, 100)),
Var = abs(rnorm(200)))
ggplot(df, aes(Var, Ele, color = Species)) +
geom_point() +
stat_ellipse(aes(fill = Species), geom="polygon",level=0.95,alpha=0.2)
Run Code Online (Sandbox Code Playgroud)
您可以编辑默认属性以将点剪辑为特定值.在这里,我们将基本属性更改为将小于0的x值修剪为0
StatClipEllipse <- ggproto("StatClipEllipse", Stat,
required_aes = c("x", "y"),
compute_group = function(data, scales, type = "t", level = 0.95,
segments = 51, na.rm = FALSE) {
xx <- ggplot2:::calculate_ellipse(data = data, vars = c("x", "y"), type = type,
level = level, segments = segments)
xx %>% mutate(x=pmax(x, 0))
}
)
Run Code Online (Sandbox Code Playgroud)
然后我们必须将它包装在一个ggplot stat中,stat_ellipe除了它使用我们的自定义Stat对象之外
stat_clip_ellipse <- function(mapping = NULL, data = NULL,
geom = "path", position = "identity",
...,
type = "t",
level = 0.95,
segments = 51,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = StatClipEllipse,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
type = type,
level = level,
segments = segments,
na.rm = na.rm,
...
)
)
}
Run Code Online (Sandbox Code Playgroud)
然后你可以用它来制作你的情节
ggplot(df, aes(Var, Ele, color = Species)) +
geom_point() +
stat_clip_ellipse(aes(fill = Species), geom="polygon",level=0.95,alpha=0.2)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
613 次 |
| 最近记录: |