R 我循环遍历数据帧,为每列绘制直方图,使用列名作为图表标题,打印第一个值
我想使用purrr::map循环浏览各个列,并为每个列打印一个直方图。这很有效R 我循环遍历数据帧,为每列绘制直方图,使用列名作为图表标题,打印第一个值,r,ggplot2,R,Ggplot2,我想使用purrr::map循环浏览各个列,并为每个列打印一个直方图。这很有效 library(tidyverse) library(patchwork) iris %>% # example data select(-Species) %>% # drop one non-numeric col map( ~ ggplot(iris, aes(x = .)) + # loop through cols... for col, take it as x aes
library(tidyverse)
library(patchwork)
iris %>% # example data
select(-Species) %>% # drop one non-numeric col
map( ~ ggplot(iris, aes(x = .)) + # loop through cols... for col, take it as x aes
geom_histogram() # graph histogram
) %>% # output is list of graphs
wrap_plots() # wrap list using patchwork
但是这些图非常神秘,没有标题来告诉你哪个图属于哪个列
我尝试添加一个标题选项
library(tidyverse)
library(patchwork)
iris %>%
select(-Species) %>%
map( ~ ggplot(iris, aes(x = .)) +
geom_histogram() +
ggtitle(.)
) %>%
wrap_plots()
但是,它打印每列的第一个值作为标题,而不是colname
head(iris, 1) # for reference
我应该采取什么不同的措施来获取colnames作为单个图形的图形标题?我也可以使用适当的x轴标签。这并不能准确回答您的问题,但如果您的用例仅限于EDA,您可以使用大量快捷方式,只需使用Skimer包即可。基本直方图打印在控制台输出中
skimr::skim(iris)
Skim summary statistics
n obs: 150
n variables: 5
-- Variable type:factor --------------------------------------------------------
variable missing complete n n_unique top_counts ordered
Species 0 150 150 3 set: 50, ver: 50, vir: 50, NA: 0 FALSE
-- Variable type:numeric -------------------------------------------------------
variable missing complete n mean sd p0 p25 p50 p75 p100 hist
Petal.Length 0 150 150 3.76 1.77 1 1.6 4.35 5.1 6.9 ▇▁▁▂▅▅▃▁
Petal.Width 0 150 150 1.2 0.76 0.1 0.3 1.3 1.8 2.5 ▇▁▁▅▃▃▂▂
Sepal.Length 0 150 150 5.84 0.83 4.3 5.1 5.8 6.4 7.9 ▂▇▅▇▆▅▂▂
Sepal.Width 0 150 150 3.06 0.44 2 2.8 3 3.3 4.4 ▁▂▅▇▃▂▁▁
这并不能准确地回答您的问题,但是如果您的用例仅是EDA,那么您可以采取大量的快捷方式,只使用Skimer包。基本直方图打印在控制台输出中
skimr::skim(iris)
Skim summary statistics
n obs: 150
n variables: 5
-- Variable type:factor --------------------------------------------------------
variable missing complete n n_unique top_counts ordered
Species 0 150 150 3 set: 50, ver: 50, vir: 50, NA: 0 FALSE
-- Variable type:numeric -------------------------------------------------------
variable missing complete n mean sd p0 p25 p50 p75 p100 hist
Petal.Length 0 150 150 3.76 1.77 1 1.6 4.35 5.1 6.9 ▇▁▁▂▅▅▃▁
Petal.Width 0 150 150 1.2 0.76 0.1 0.3 1.3 1.8 2.5 ▇▁▁▅▃▃▂▂
Sepal.Length 0 150 150 5.84 0.83 4.3 5.1 5.8 6.4 7.9 ▂▇▅▇▆▅▂▂
Sepal.Width 0 150 150 3.06 0.44 2 2.8 3 3.3 4.4 ▁▂▅▇▃▂▁▁
更新:使用
map2()
的解决方案如下。通过将列名提取到一个单独的向量中作为.y
参数,我们可以使用它作为xlab()
的参数
…以及输出:
原始帖子:一个带有lappy()
的解决方案如下所示
chartList <- lapply(1:4,function(y){
ggplot(iris, aes(x = iris[[y]])) +
geom_histogram() +
ggtitle(colnames(iris[y]))
})
wrap_plots(chartList)
更新:使用
map2()
的解决方案如下所示。通过将列名提取到一个单独的向量中作为.y
参数,我们可以使用它作为xlab()
的参数
…以及输出:
原始帖子:一个带有lappy()
的解决方案如下所示
chartList <- lapply(1:4,function(y){
ggplot(iris, aes(x = iris[[y]])) +
geom_histogram() +
ggtitle(colnames(iris[y]))
})
wrap_plots(chartList)
如果使用map2()
可以引用管道中的第二个列名向量,如我的答案所示。如果使用map2()
可以引用管道中的第二个列名向量,如我的答案所示。