r - Constrict ggplot ellips to realistic/possible values -
when plotting ellips ggplot possible constrain ellips values possible?
for example, following reproducible code , data plots ele vs. var 2 species. var positive variable , cannot negative. nonetheless, negative values included in resulting ellips. possible bound ellips 0 on x-axis (using ggplot)?
more specifically, picturing flat edge ellipsoids truncated @ 0 on x-axis.
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)
you edit default stat clip points particular value. here change basic stat trim x values less 0 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)) } ) then have wrap in ggplot stat identical stat_ellipe except uses our custom stat object
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, ... ) ) } then can use make plot
ggplot(df, aes(var, ele, color = species)) + geom_point() + stat_clip_ellipse(aes(fill = species), geom="polygon",level=0.95,alpha=0.2) this inspired source code stat_ellipse.


Comments
Post a Comment