R 用KDE代替plotly中的直方图绘制二维密度等值线图

R 用KDE代替plotly中的直方图绘制二维密度等值线图,r,plotly,contour,kernel-density,R,Plotly,Contour,Kernel Density,大家好:我想用R plotly绘制密度等值线图,而不是二维密度等值线图。有人能帮我吗?下面是我的数据和代码 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,

大家好:我想用R plotly绘制密度等值线图,而不是二维密度等值线图。有人能帮我吗?下面是我的数据和代码

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)

g您可以使用
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)
den_x也许这篇文章会对你有所帮助