Created
July 18, 2018 14:35
-
-
Save timriffe/9df98abdda7a21a49c19c58155167491 to your computer and use it in GitHub Desktop.
quick code to draw points with a blur parameter that scales to some notion of a standard deviation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# blur point. | |
add_alpha <- function(col, alpha = .5){ | |
if (all(col %in% colors())){ | |
r.g.b. <- t(col2rgb(col))/255 | |
} else { | |
r.g.b. <- as.matrix(colorspace::hex2RGB(col, gamma = FALSE)@coords) | |
} | |
cola <- apply(r.g.b., 1, | |
function(x) | |
rgb(x[1], x[2], x[3], alpha=alpha)) | |
cola | |
} | |
get_asp <- function(){ | |
diff(par("usr")[1:2]) / diff(par("usr")[3:4]) * | |
par("pin")[2] / par("pin")[1] | |
} | |
blurpoint <- function( | |
x, | |
y, | |
col, # color: named or hex (alpha ignored and reapplied using alpha arg) | |
sd = 1, # standard deviation | |
cex = 1, # standard cex (relative to unit circle) | |
N = 500, # Number of verticies | |
maxq = 1, # blur out to 100% quantile? 1 = Inf, so this means until .99 in practice. | |
asp.adjust = TRUE, # adjust for non-unity aspect so that circles guaranteed? | |
alpha = .01, # alpha as prop. | |
ci95 = TRUE, # draw ring at 95ci | |
ctr = FALSE){ # add point to centroid? | |
# x,y centroid | |
# col = base color, to interoplate toward bg | |
# sd, standard dev to represent as blur | |
# cex = common multiplier of point size | |
# N, how many vertices | |
# radians | |
rads <- c(seq(0, 2 * pi, length = N - 1), 2 * pi) | |
ux <- cos(rads) | |
uy <- sin(rads) | |
radii <- qnorm(seq(.5, maxq, length = 100),sd=sd)[-100] | |
xx <- outer(ux, radii) * cex + x | |
# adjust for non-unity aspect ratio, so that circles always circles? | |
asp <- ifelse(asp.adjust, 1/get_asp(),1) | |
yy <- outer(uy, radii) * cex * asp + y | |
cola <- add_alpha(col, alpha=alpha) | |
for (i in 1:ncol(xx)){ | |
polygon(xx[, i], yy[, i], border = FALSE, col = cola) | |
} | |
# ring as 95% | |
if (ci95){ | |
r95 <- qnorm(.975, sd = sd) * cex | |
polygon(x = (ux * r95) + x, | |
y = (uy * r95 * asp) + y, | |
border = col, | |
lwd = .8) | |
} | |
if (ctr){ | |
points(x,y,cex=.5,pch=16,col=col) | |
} | |
} | |
plot(NULL, type = 'n', xlim = c(0,35), ylim = c(0,55), asp=2, ann = FALSE, las = 1) | |
blurpoint(15,15,col="#FF0000",sd=.5,cex=2,ci95=FALSE) | |
blurpoint(5,15,col="#FF0000",sd=1,cex=1,ci95=FALSE,ctr=TRUE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment