简体   繁体   English

具有KDE的2D密度等高线图,而不是绘图中的直方图

[英]2D Density Contour Plot with KDE instead of histogram in plotly

Hi all: I would like to draw kernel density instead of histograms in 2D Density Contour Plot using R plotly. 大家好:我想用R在2D密度轮廓图中绘制内核密度而不是直方图 Could anyone help me, please? 有人可以帮我吗? Below are my data and code. 以下是我的数据和代码。

g <-c("Pla", "Ond","Gra", "Dol","Tro", "Ond+Dex", "Pal","Ram", "Ond+Drop",  "Ond+Met", "Gra+Dex",  "Pal+Dex", "Dol+Dex", "Dol+Drop", "Gran+Drop")
s1<-c(51.9, 64.9, 93.5, 27.7, 35.3, NA, NA, NA, NA, NA, NA, NA, 26.6, NA, NA)
s2<-c(0.8, 25.4, 44.8, 13.3, 23.2, 71.9, 54.9, 51.3, 65.4, 52.8, 81.2, 43.7, 72.8, 76.8, 71.7)
s3<-c(0.1, 20.1, 42.5, 37.7, 16.3, 63, 72.3, 34.9, 76.9, NA, 86.3, 67, NA, 71.9, 61.1)
mydata<-data.frame(g, s1, s2, s3)
rownames(mydata) <- mydata[,1]
mydata <- mydata[,-1]

s <- subplot(
  plot_ly(mydata, x = ~s1, type = "histogram"),
  plotly_empty(mydata),
  plot_ly(mydata, x = ~s1, y = ~s2, z = ~s3, type = "contour"),
  plot_ly(mydata, y = ~s2, type = "histogram"),
  nrows = 2, heights = c(0.2, 0.8), widths = c(0.8, 0.2), margin = 0,
  shareX = TRUE, shareY = TRUE, titleX = FALSE, titleY = FALSE
)
p <- layout(s, showlegend = FALSE)

You can use the density function to generate kernel density estimates, and then plot these as line graphs as follows: 您可以使用density函数生成内核密度估计,然后将它们绘制为线形图,如下所示:

den_x <- density(mydata$s1, na.rm=TRUE)
den_x <- data.frame(x=den_x$x, y=den_x$y)

den_y <- density(mydata$s2, na.rm=TRUE)
den_y <- data.frame(x=den_y$x, y=den_y$y)

s <- subplot(
  plot_ly(den_x, x = ~x, y = ~y, type = "scatter", mode="lines"),
  plotly_empty(mydata),
  plot_ly(mydata, x = ~s1, y = ~s2, z = ~s3, type = "contour"),
  plot_ly(den_y, x = ~y, y = ~x, type = "scatter", mode="lines"),
  nrows = 2, heights = c(0.2, 0.8), widths = c(0.8, 0.2), margin = 0,
  shareX = TRUE, shareY = TRUE, titleX = FALSE, titleY = FALSE
)
p <- layout(s, showlegend = FALSE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM