r - Mapping variables to hexagon size and color with hex_bin -
r - Mapping variables to hexagon size and color with hex_bin -
so, found this code how map variable hexagon size while ago , tried modify utilize purpose of drawing basketball shot charts. know there have been other threads this one, none i've read in past answered question. first 1 help i'm stuck 1 little problem:
let's have info frame 4 variables, x, y, value (of points shot has; in basketball it's either 2 or 3, depending on how far basket take shot), , outcome (1 shot made, 0 shot missed), on 250 observations. 250 shots x , y coordinates, value , outcome.
example:
x y value outcome 1 169.7650 -316.5726 3 0 2 75.0775 -182.3126 2 0 3 94.0150 -147.4050 2 1 4 109.1650 -138.0068 2 0 5 87.7025 -146.0624 2 1 # dput below: structure(list(x = c(169.765, 75.0775, 94.015, 109.165, 87.7025), y = c(-316.5726, -182.3126, -147.405, -138.0068, -146.0624), value = c(3l, 2l, 2l, 2l, 2l), outcome = c(0l, 0l, 1l, 0l, 1l)), .names = c("x", "y", "value", "outcome"), class = "data.frame", row.names = c(na, -5l))
negative coordinates because (0/0) in top left corner. code first thread linked above able bin data, can't figure out how operate on binned data. got far:
from code:
# devtools::install_git("https://github.com/hadley/densityvis.git") library(densityvis) bin = hex_bin(df$x, df$y, var4=df$value, frequency.to.area=true) hexes = hex_coord_df(x=bin$x, y=bin$y, width=attr(bin,"width"), height=attr(bin,"height"), size=bin$size) hexes$rightness = rep(bin$col, each=6) ggplot(hexes, aes(x=x, y=y)) + geom_polygon(aes(fill=rightness, group=id))
with size displaying how many shots taken given area. color gives value of shots area. want points per shot, meaning: summing points per bin , dividing number of shots taken, ranging 0 (no shots made) 3 (all shots made 3 point area) , displaying bins @ to the lowest degree 2 shots taken.
i know lot ask, , it's problem can't on own. if had time, help much appreciated.
edit: uploaded csv sample created above image here. don't know if it's cool post 300 lines of code question, that's why link geotheory's code here. modified illustration in code bracket above, ran
df <- read.csv("sample_data.csv", header=true)
beforehand.
as hex_bin code stands 0 value observations filtered out. can changed removing & var4 > 0
argument clean_xy
(line 117 in github). following:
df$pts = 0 for(i in 1:nrow(df)) if(df$outcome[i] == 1) df$pts[i] = df$value[i] bin = hex_bin(df$x, df$y, var4=df$pts, frequency.to.area=true) hexes = hex_coord_df(x=bin$x, y=bin$y, width=attr(bin,"width"), height=attr(bin,"height"), size=bin$size) hexes$points = rep(bin$col, each=6) ggplot(hexes, aes(x=x, y=y)) + geom_polygon(aes(fill=points, group=id))
gives you:
is you're looking for?
r ggplot2 binning
Comments
Post a Comment