How do I generate a histogram for each column of my table?

时间:2016-02-12 21:19:24

标签: r ggplot2

I have a table of data with a column representing a lab value for each study subject (rows).

I want to generate a series of histograms showing the distribution of values for each lab test (i.e. column). Each set of lab values would ideally have a different bin width (some are integers with a range of hundreds, some are numeric with a range of 2-3).

How do I do that?

3 个答案:

答案 0 :(得分:20)

如果您合并tidyrggplot2个包,则可以使用facet_wrap为data.frame中的每个变量制作一组快速直方图。

您需要使用tidyr::gather将数据重新整形为长格式,这样您就可以拥有keyvalue列:

library(tidyr)
library(ggplot2)
# or `library(tidyverse)`

mtcars %>% gather() %>% head()
#>   key value
#> 1 mpg  21.0
#> 2 mpg  21.0
#> 3 mpg  22.8
#> 4 mpg  21.4
#> 5 mpg  18.7
#> 6 mpg  18.1

将此作为我们的数据,我们可以将value映射为x变量,并使用facet_wrapkey列分隔开来:

ggplot(gather(mtcars), aes(value)) + 
    geom_histogram(bins = 10) + 
    facet_wrap(~key, scales = 'free_x')

除非您的数据具有相似的比例,否则scales = 'free_x'是必要的。

您可以将bins = 10替换为评估为数字的任何内容,这可能允许您通过一些创造力单独设置它们。或者,您可以设置binwidth,这可能更实用,具体取决于您的数据。无论如何,装箱将需要一些技巧。

答案 1 :(得分:5)

如果您的数据框名为“df”并且您想要生成从第2列开始的直方图(如果第1列是您的ID),您可以在for循环中生成类似这样的图:

for (col in 2:ncol(df)) {
    hist(df[,col])
}

hist函数自动计算合理的bin宽度,或者你可以通过添加breaks参数为所有直方图指定固定数量的bin:

hist(df[,col], breaks=10)

如果您使用RStudio,您的所有绘图将自动保存在绘图窗格中。如果没有,您需要将每个绘图保存到循环内的单独文件中,如下所述:http://www.r-bloggers.com/automatically-save-your-plots-to-a-folder/

答案 2 :(得分:0)

我刚遇到multi.hist() function from the psych package。它使您可以按特定列快速绘制直方图,并且看起来可以为每列设置不同的中断。

相关问题