R|可视化|边缘直方图
2021-02-27 本文已影响0人
高大石头
在分类数据变量展示时,如果能在边缘展示直方图就更完美了。下面我们就来学习下用ggExtra来 添加边缘直方图(marginal histograms)。
环境配置
library(tidyverse)
library(ggExtra)
theme_set(theme_bw(16)) #设置背景色为dark-on-light,基础字体为16
library(palmerpenguins)
colnames(penguins)
## [1] "species" "island" "bill_length_mm"
## [4] "bill_depth_mm" "flipper_length_mm" "body_mass_g"
## [7] "sex" "year"
基础绘图
p1 <- penguins %>%
ggplot(aes(bill_length_mm,body_mass_g,color=species))+
geom_point()+
theme(legend.position = "none")
p1
边缘直方图
ggMarginal(p1,type = "histogram",groupColour = TRUE,groupFill = TRUE)
ggMarginal核心参数:
ggMarginal(p, data, x, y, type = c("density", "histogram", "boxplot", "violin", "densigram"), margins = c("both", "x", "y"), ..., groupColour = FALSE,groupFill = FALSE)
p: ggplot2 scatterplot对象,如果未提供,需要data,x和y
type:边缘图形展示的方式,有density,histogram,boxplot,densigram类型
margins:需要哪个边缘进行展示,x轴,y轴或者都展示
groupColour: 按照group着色
groupFill: 按照group填充
#当需要加图注时最好在左侧,这样显得比较合理,否则边缘图夹在中间,显得不太协调。
p2 <- penguins %>%
ggplot(aes(bill_length_mm,body_mass_g,color=species))+
geom_point()+
theme(legend.position = "left")
ggMarginal(p2,type = "histogram",groupColour = TRUE,groupFill = TRUE)
Session Info
sessionInfo()
## R version 4.0.3 (2020-10-10)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 18363)
##
## Matrix products: default
##
## locale:
## [1] LC_COLLATE=Chinese (Simplified)_China.936
## [2] LC_CTYPE=Chinese (Simplified)_China.936
## [3] LC_MONETARY=Chinese (Simplified)_China.936
## [4] LC_NUMERIC=C
## [5] LC_TIME=Chinese (Simplified)_China.936
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] palmerpenguins_0.1.0 ggExtra_0.9 forcats_0.5.0
## [4] stringr_1.4.0 dplyr_1.0.2 purrr_0.3.4
## [7] readr_1.4.0 tidyr_1.1.2 tibble_3.0.4
## [10] ggplot2_3.3.2 tidyverse_1.3.0
##
## loaded via a namespace (and not attached):
## [1] Rcpp_1.0.5 lubridate_1.7.9.2 assertthat_0.2.1 digest_0.6.27
## [5] mime_0.9 R6_2.5.0 cellranger_1.1.0 backports_1.2.0
## [9] reprex_0.3.0 evaluate_0.14 httr_1.4.2 pillar_1.4.7
## [13] rlang_0.4.9 readxl_1.3.1 rstudioapi_0.13 miniUI_0.1.1.1
## [17] rmarkdown_2.5 labeling_0.4.2 munsell_0.5.0 shiny_1.5.0
## [21] broom_0.7.2 compiler_4.0.3 httpuv_1.5.4 modelr_0.1.8
## [25] xfun_0.19 pkgconfig_2.0.3 htmltools_0.5.0 tidyselect_1.1.0
## [29] fansi_0.4.1 crayon_1.3.4 dbplyr_2.0.0 withr_2.3.0
## [33] later_1.1.0.1 grid_4.0.3 jsonlite_1.7.1 xtable_1.8-4
## [37] gtable_0.3.0 lifecycle_0.2.0 DBI_1.1.0 magrittr_2.0.1
## [41] scales_1.1.1 cli_2.2.0 stringi_1.5.3 farver_2.0.3
## [45] fs_1.5.0 promises_1.1.1 xml2_1.3.2 ellipsis_0.3.1
## [49] generics_0.1.0 vctrs_0.3.5 tools_4.0.3 glue_1.4.2
## [53] hms_0.5.3 prettydoc_0.4.0 fastmap_1.0.1 yaml_2.2.1
## [57] colorspace_2.0-0 rvest_0.3.6 knitr_1.30 haven_2.3.1
参考链接:
https://datavizpyr.com/how-to-make-scatterplot-with-marginal-histograms-in-r/