R语言 | 2d概率密度分布图

1个变量的分布可以用hist,两个变量呢?可以用等高线图、登高颜色图。

1. 效果图

在这里插入图片描述

2. 源代码

# 2d概率密度图
library(ggplot2)
p1=ggplot(faithful, aes(eruptions, waiting) )

plots=list()

#1. 散点图
plots[[1]]=p1 + 
  geom_point(colour = "black") + 
  theme_bw()+ggtitle("1")

# 等高线图
plots[[2]]=p1 + 
  stat_density2d(color = "black", size = 1) + 
  theme_bw()+ggtitle("2")

# 散点图+等高线
plots[[3]]=p1 +
  stat_density2d(color = "black", size = 1) + 
  geom_point(colour = "black") + 
  theme_bw()+ggtitle("3")


# 将密度映射到等高线
plots[[4]]=p1 +
  #stat_density2d(aes(color = ..level..), size = 1.5) + 
  stat_density2d(aes(color = after_stat(level) ), linewidth = 1.5) + 
  geom_point(colour = "black") + 
  scale_color_distiller(palette = "RdYlGn") + 
  theme_bw()+ggtitle("4")


#2. geom = "tile" 绘制颜色表示的密度图
plots[[5]]=p1 +
  stat_density2d(geom = "tile", aes(fill = ..density..), contour = FALSE) + 
  scale_fill_distiller(palette = "RdYlGn") + 
  theme_classic()+ggtitle("5")

# geom = "raster" 同上,栅格化
plots[[6]]=p1 +
  stat_density2d(geom = "raster", aes(fill = ..density..), contour = FALSE) + 
  scale_fill_distiller(palette = "RdYlGn")  + 
  theme_bw()+ggtitle("6")

# 对带宽进行调整
plots[[7]]=p1 +
  stat_density2d(geom = "raster", aes(fill = ..density..), 
                 contour = FALSE, 
                 h = c(1, 5)) +  # 修改带宽,h参数传参给 kde2d()产生密度估计 >?kde2d
  scale_fill_distiller(palette = "RdYlGn")  + 
  theme_bw()+ggtitle("7")
#h	 Bandwidth (vector of length two). If NULL, estimated using MASS::bandwidth.nrd().

# 3. 综合
plots[[8]]=p1 +
  stat_density2d(geom = "raster", aes(fill = ..density..), contour = FALSE) + 
  stat_density2d(color = "black", size = 0.7) + 
  geom_point(colour = "black", size=1) + 
  scale_fill_distiller(palette = "RdYlGn")  + 
  theme_classic()+ggtitle("8")

# 细节调整
plots[[9]]=p1 +
  stat_density2d(geom = "raster", aes(fill = ..density..), contour = F) + 
  #stat_density2d(color = "black", size = 0.6, bins=8) + 
  stat_density2d(color = "black", size = 0.6, binwidth=0.0035) + 
  geom_point(colour = "black", size=0.8) + 
  scale_fill_gradient2(low = "navy", 
                      mid = "#FFF200", midpoint = 0.012,
                      high="#ED1C24")  +
  theme_classic()+ggtitle("9")

# 拼接图
patchwork::wrap_plots(plots, ncol = 3)

Ref

  • https://r-graphics.org/RECIPE-DISTRIBUTION-DENSITY2D.html
  • https://r-graphics.org/RECIPE-DISTRIBUTION-BASIC-DENSITY.html
绘制概率密度分布图是数据分析中常见的任务之一,特别是在统计学和数据可视化领域。Python 提供了多种工具和库来完成这项任务,其中最常用的是 `Matplotlib`、`Seaborn` 和 `SciPy`。以下是几种常见方法。 ### 使用 Matplotlib 绘制一维概率密度分布图 `Matplotlib` 是 Python 中最基础的绘图库,可以通过 `plt.plot()` 和 `scipy.stats.gaussian_kde` 来绘制概率密度曲线。 ```python import numpy as np import matplotlib.pyplot as plt from scipy.stats import gaussian_kde # 生成示例数据 data = np.random.normal(size=1000) # 创建密度估计器 density = gaussian_kde(data) # 生成 x 轴数据 x = np.linspace(min(data), max(data), 1000) # 绘制密度图 plt.plot(x, density(x)) plt.fill_between(x, density(x), alpha=0.2) plt.title("1D Probability Density Distribution") plt.xlabel("Value") plt.ylabel("Density") plt.grid(True) plt.show() ``` ### 使用 Seaborn 绘制一维概率密度分布图 `Seaborn` 是基于 `Matplotlib` 的高级接口,提供了更简洁的 API 来绘制密度图。 ```python import seaborn as sns import numpy as np # 生成示例数据 data = np.random.normal(size=1000) # 使用 Seaborn 绘制密度图 sns.kdeplot(data, shade=True) plt.title("1D Probability Density Distribution using Seaborn") plt.xlabel("Value") plt.ylabel("Density") plt.grid(True) plt.show() ``` ### 使用 Matplotlib 和 Numpy 绘制二维概率密度分布图 对于二维数据集,可以使用 `gaussian_kde` 和 `contourf` 来绘制二维密度图。 ```python import numpy as np import matplotlib.pyplot as plt from scipy.stats import gaussian_kde # 生成二维示例数据 x = np.random.normal(0, 1, 1000) y = np.random.normal(0, 1, 1000) # 创建二维密度估计器 xy = np.vstack([x, y]) density = gaussian_kde(xy) # 生成网格数据 X, Y = np.mgrid[x.min():x.max():100j, y.min():y.max():100j] positions = np.vstack([X.ravel(), Y.ravel()]) Z = np.reshape(density(positions).T, X.shape) # 绘制二维密度图 plt.contourf(X, Y, Z, cmap='viridis') plt.colorbar(label='Density') plt.title("2D Probability Density Distribution") plt.xlabel("X") plt.ylabel("Y") plt.grid(True) plt.show() ``` ### 使用 Seaborn 绘制二维概率密度分布图 `Seaborn` 也支持二维密度图,使用 `jointplot` 或 `kdeplot`。 ```python import seaborn as sns import numpy as np # 生成二维示例数据 x = np.random.normal(0, 1, 1000) y = np.random.normal(0, 1, 1000) # 使用 Seaborn 绘制二维密度图 sns.jointplot(x=x, y=y, kind="kde", space=0, cmap="viridis") plt.suptitle("2D Probability Density Distribution using Seaborn") plt.tight_layout() plt.show() ``` ### 其他工具 - **Plotly**:交互式绘图工具,适合在 Web 环境中展示。 - **Altair**:声明式可视化工具,语法简洁,适合快速生成图表。 - **Bokeh**:支持大规模数据的交互式可视化工具。 这些方法可以根据具体需求选择使用,例如是否需要交互性、是否需要支持大规模数据等。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值