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

相关推荐
计算机安禾5 分钟前
【c++面向对象编程】第40篇:单例模式(Singleton)的多种C++实现
开发语言·c++·单例模式
_日拱一卒20 分钟前
LeetCode:114二叉树展开为链表
java·开发语言·算法
天天进步201523 分钟前
从零打造 Python 全栈项目:智能教学辅助系统
开发语言·人工智能·python
kkeeper~39 分钟前
0基础C语言积跬步之内存函数
c语言·开发语言
吃好睡好便好40 分钟前
在Matlab中绘制杆状图
开发语言·学习·算法·matlab·信息可视化
桀人44 分钟前
C++——内存管理——new和delete的超详细解析
开发语言·c++
Shadow(⊙o⊙)1 小时前
Shell进程替换,自定义Shell解释器——字符串库函数灵活操作!
linux·运维·服务器·开发语言·c++·学习
数智工坊1 小时前
PyCharm 运行 Python 脚本总自动进 Test 模式?附 RT-DETRv2 依赖缺失终极排坑
开发语言·ide·人工智能·python·pycharm
再写一行代码就下班1 小时前
根据给定word模板,动态填充指定内容,并输出为新的word文档。(${aa}占位符方式且支持循环动态表格)
java·开发语言
七夜zippoe1 小时前
DolphinDB流数据表:创建与订阅
开发语言·订阅··dolphindb·数据表