【问题标题】:2D Density Contour Plot with KDE instead of histogram in plotly使用 KDE 代替直方图的 2D 密度等高线图
【发布时间】:2017-11-21 06:34:05
【问题描述】:

大家好:我想在二维密度等高线图中使用 R 绘制 kernel density 而不是 histograms。有人可以帮我吗?以下是我的数据和代码。

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)

【问题讨论】:

标签: r plotly contour kernel-density


【解决方案1】:

您可以使用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)

【讨论】:

    猜你喜欢
    • 2015-11-05
    • 2020-04-29
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多