R | 可视化 | 二维密度图(2D Density Plot)
作者:互联网
2D密度图对研究2个数字变量之间的关系很有用,尤其是有大量的点,这篇文章将介绍几种类型的二维密度图,并且尝试用不同方法绘制。
1 geom_point()绘制二维散点图
> install.packages("tidyverse")
> library(tidyverse)
# 创建数据
> a <- data.frame( x=rnorm(30000, 12, 1.9), y=rnorm(30000, 9, 1.2) )
> b <- data.frame( x=rnorm(30000, 15.5, 1.9), y=rnorm(30000, 12.5, 1.9) )
> c <- data.frame( x=rnorm(30000, 9, 1.9), y=rnorm(30000, 15.5, 1.9) )
> data <- rbind(a,b,c)
# 绘制基础散点图
> ggplot(data, aes(x=x, y=y) )
+ geom_point()
OUTPUT:
2 geom_bin2d()绘制二维直方图
2.1基础绘制
> library(tidyverse)
# 创建数据
> a <- data.frame( x=rnorm(30000, 12, 1.9), y=rnorm(30000, 9, 1.2) )
> b <- data.frame( x=rnorm(30000, 15.5, 1.9), y=rnorm(30000, 12.5, 1.9) )
> c <- data.frame( x=rnorm(30000, 9, 1.9), y=rnorm(30000, 15.5, 1.9) )
> data <- rbind(a,b,c)
# 绘制基础2d直方图
> ggplot(data, aes(x=x, y=y) )
+ geom_bin2d()
+ theme_bw()
OUTPUT:
2.2 参数修改
# 修改颜色和bin大小
> ggplot(data, aes(x=x, y=y) )
+ geom_bin2d(bins = 90)
+ scale_fill_continuous(type = "viridis")
+ theme_bw()
OUTPUT:
3 geom_hex()
绘制六边形图(Hexbin Plot)
# 绘制六边形图及参数自定义
> ggplot(data, aes(x=x, y=y) )
+ geom_hex(bins = 90)
+ scale_fill_continuous(type = "viridis")
+ theme_bw()
OUTPUT:
4 stat_density_2d绘制二维密度图
4.1 基础绘制二维密度图
# geom参数设置区域,color参数设置轮廓线
> ggplot(data, aes(x=x, y=y) )
+ stat_density_2d(aes(fill = ..level..), geom = "polygon", colour="white")
OUTPUT:
4.2 使用raster光栅显示
> ggplot(data, aes(x=x, y=y) )
+ stat_density_2d(aes(fill = ..density..), geom = "raster", contour = FALSE)
+ scale_x_continuous(expand = c(0, 0))
+ scale_y_continuous(expand = c(0, 0))
OUTPUT:
4.3 自定义调色盘等,可以用数字或名称定义
> ggplot(data, aes(x=x, y=y) )
+ stat_density_2d(aes(fill = ..density..), geom = "raster", contour = FALSE)
+ scale_fill_distiller(palette=4, direction=1)
+ scale_x_continuous(expand = c(0, 0))
+ scale_y_continuous(expand = c(0, 0))
+ theme(
+ legend.position='none'
+ )
OUTPUT:
> ggplot(data, aes(x=x, y=y) )
+ stat_density_2d(aes(fill = ..density..), geom = "raster", contour = FALSE)
+ scale_fill_distiller(palette= "Spectral", direction=1)
+ scale_x_continuous(expand = c(0, 0))
+ scale_y_continuous(expand = c(0, 0))
+ theme(
+ legend.position='none'
+ )
OUTPUT:
标签:Plot,aes,scale,Density,density,2D,geom,OUTPUT,data 来源: https://blog.csdn.net/Luminoll/article/details/122742723