8.6 密度图

heatmaps in ggplot2 二维密度图

ggplot(faithful, aes(x = eruptions, y = waiting)) +
  stat_density_2d(aes(fill = ..level..), geom = "polygon") +
  xlim(1, 6) +
  ylim(40, 100)

ggplot(faithful, aes(x = eruptions, y = waiting)) +
  stat_density2d(aes(fill = stat(level)), geom = "polygon") +
  scale_fill_viridis_c(option = "viridis") +
  xlim(1, 6) +
  ylim(40, 100)
二维密度图二维密度图

图 8.9: 二维密度图

MASS::kde2d() 实现二维核密度估计,ggplot2 包提供了两种等价的绘图方式

  1. stat_density_2d()..
  2. stat_density2d()stat()
plotly::plot_ly(
  data = faithful, x = ~eruptions,
  y = ~waiting, type = "histogram2dcontour"
) %>%
  plotly::config(displayModeBar = FALSE)

图 8.10: 二维直方图/密度图/轮廓图

# plot_ly(faithful, x = ~waiting, y = ~eruptions) %>% 
#   add_histogram2d() %>% 
#   add_histogram2dcontour()

延伸一下,热力图

library(KernSmooth)
den <- bkde2D(x = faithful, bandwidth = c(0.7, 7))
# 热力图
p1 <- plotly::plot_ly(x = den$x1, y = den$x2, z = den$fhat) %>%
  plotly::config(displayModeBar = FALSE) %>%
  plotly::add_heatmap()

# 等高线图
p2 <- plotly::plot_ly(x = den$x1, y = den$x2, z = den$fhat) %>%
  plotly::config(displayModeBar = FALSE) %>%
  plotly::add_contour()

htmltools::tagList(p1, p2)