Skip to content

Commit

Permalink
make label optional
Browse files Browse the repository at this point in the history
  • Loading branch information
mschubert committed Nov 30, 2023
1 parent 86eb76c commit 77919ac
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions plot/denspt.r
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,32 @@
#' @param pal_alpha The transparency of the density layer
denspt = function(data, mapping, n_tile=50, draw_pt=500, nodens=500, draw_label=60, always_label=c(),
tsize=NULL, max_ov=25, h=15, ..., palette="Greys", pal_dir=1, pal_alpha=1) {
mis_map = setdiff(c("x", "y", "label"), names(mapping))
mis_map = setdiff(c("x", "y"), names(mapping))
if (length(mis_map) > 0)
stop("Missing mapping: ", paste(mis_map, collapse=", "))

lx = rlang::as_name(mapping$x)
ly = rlang::as_name(mapping$y)
ll = rlang::as_name(mapping$label)
keep = apply(data[c(lx, ly)], 1, function(x) !any(is.na(x) | is.infinite(x)))
data = data[keep,]
x = data[[lx]]
y = data[[ly]]

h = c(diff(range(x, na.rm=TRUE))/h[1], diff(range(y, na.rm=TRUE))/rev(h)[1])
dens = MASS::kde2d(x, y, h, n=n_tile)
data$dens = fields::interp.surface(dens, data.frame(x=x, y=y))
data$draw_pt = ifelse(rank(data$dens)<draw_pt, "pt", NA)
data[[ll]] = ifelse(rank(data$dens)<draw_label | data[[ll]] %in% always_label, data[[ll]], NA)
if (is.null(tsize))
tsize = 1.5 + 5 * 1/sqrt(mean(nchar(data[[ll]]), na.rm=TRUE))

if ("label" %in% names(mapping)) {
ll = rlang::as_name(mapping$label)
data[[ll]] = ifelse(rank(data$dens)<draw_label | data[[ll]] %in% always_label, data[[ll]], NA)
if (is.null(tsize))
tsize = 1.5 + 5 * 1/sqrt(mean(nchar(data[[ll]]), na.rm=TRUE))
draw_label = ggrepel::geom_label_repel(max.overlaps=max_ov, size=tsize,
min.segment.length=0, segment.alpha=0.3, fill="#ffffffa0", label.size=NA,
max.iter=1e6, max.time=10, label.padding = unit(0.12, "lines"),
box.padding = unit(0.01, "lines"), na.rm=TRUE)
} else
draw_label = list()

dens_geom = list()
if (nrow(data) > nodens)
Expand All @@ -44,10 +51,7 @@ denspt = function(data, mapping, n_tile=50, draw_pt=500, nodens=500, draw_label=
geom_vline(xintercept=0, color="grey", linetype="dashed") +
geom_point(aes(shape=draw_pt, ...)) +
geom_smooth(color="blue", method="lm", se=FALSE) +
ggrepel::geom_label_repel(max.overlaps=max_ov, size=tsize,
min.segment.length=0, segment.alpha=0.3, fill="#ffffffa0", label.size=NA,
max.iter=1e6, max.time=10, label.padding = unit(0.12, "lines"),
box.padding = unit(0.01, "lines"), na.rm=TRUE) +
draw_label +
scale_fill_distiller(palette=palette, trans="log10",
breaks=c(1,10,50,200,1000,5000,20000), direction=pal_dir) +
scale_shape_manual(values=c(pt=19)) +
Expand Down

0 comments on commit 77919ac

Please sign in to comment.