在R中的Plotly中自定义3D内核密度图的颜色?

时间:2018-07-17 23:07:07

标签: r kernel-density r-plotly

我正在使用以下代码生成Steph Curry拍摄数据的3D核密度图:

library(rjson)
library(jsonlite)
library(RCurl)

url = "http://stats.nba.com/stats/shotchartdetail?CFID=33&CFPARAMS=2017-18&ContextFilter=&ContextMeasure=FGA&DateFrom=&DateTo=&GameID=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PaceAdjust=N&PerMode=PerGame&Period=0&PlayerID=201939&PlusMinus=N&PlayerPosition=&Rank=N&RookieYear=&Season=2017-18&SeasonSegment=&SeasonType=Regular%20Season&TeamID=0&VsConference=&VsDivision="

content = getURLContent(url, verbose = TRUE, useragent = getOption("HTTPUserAgent"))

shot.data <- fromJSON( txt = content )               

steph_curry <- as.data.frame(shot.data$resultSets$rowSet[[1]], stringsAsFactors = FALSE )

colnames(steph_curry) <- shot.data$resultSets$headers[[1]]

library(plotly)
library(MASS)

steph_curry$LOC_X = as.numeric(steph_curry$LOC_X)
steph_curry$LOC_Y = as.numeric(steph_curry$LOC_Y)
steph_curry$SHOT_MADE_FLAG = as.numeric(steph_curry$SHOT_MADE_FLAG)

den3d <- kde2d(steph_curry$LOC_X,steph_curry$LOC_Y)

plot_ly(x=den3d$x, y=den3d$y, z=den3d$z) %>% add_surface() 

以上所有代码都可以正常工作。接下来,我要做的是根据目标百分比而不是内核密度的z值对图形进行颜色编码。我使用以下代码通过创建射击数据的六边形来生成这些射门得分百分比的数据帧,其中每个六边形的z值都是射击百分比,然后在内核密度中为每个x,y配对分配六边形的z值,是最小的笛卡尔距离。同样,我可以使用以下代码成功完成此操作:

playermeans = den3d$z
row.names(playermeans) = den3d$x
colnames(playermeans) = den3d$y

a = hexbin(x = steph_curry$LOC_X,y=steph_curry$LOC_Y,IDs = TRUE,xbins = 10)
b = hexTapply(a,steph_curry$SHOT_MADE_FLAG,FUN = mean)

hexmeans=NULL
hexmeans$X = a@xcm
hexmeans = as.data.frame(means)
hexmeans$Y = a@ycm
hexmeans$Z = b

playermeans = as.data.frame(playermeans)

for(i in 1:nrow(playermeans)){
  for (j in 1:ncol(playermeans)){
    x_coord = as.numeric(rownames(playermeans)[i])
    y_coord = as.numeric(colnames(playermeans)[j])
    dists <- (x_coord - hexmeans$X)^2 + (y_coord - hexmeans$Y)^2
    playermeans[i,j] = hexmeans$Z[dists == min(dists)]
  }
}

剩下的唯一要做的就是根据playermeans变量中的射击百分比分配颜色渐变。假设有可能,我该怎么做?

0 个答案:

没有答案