简体   繁体   English

R:绘制 data.frame 中所有列的直方图

[英]R: plot histogram of all columns in a data.frame

I'm a new user in R and I've just started to work with it to see the distribution of my data but I got stuck on this error.我是 R 的新用户,我刚刚开始使用它来查看我的数据的分布,但我遇到了这个错误。 I have a data frame and I would like to plot histograms of it's numeric columns.我有一个数据框,我想绘制它的数字列的直方图。 So what I did is as bellow :所以我所做的是如下:

num_data <-my_data[, sapply(my_data, is.numeric)] 
for (i in 1:length(names(num_data))){
  print(i)
  hist( num_data[i], main='hist', breaks=20, prob=TRUE)
}

But I get the error 'Error in hist.default(num_data[i], main = "hist", breaks = 20, prob = TRUE) : 'x' must be numeric ' I checked the type of num_data[i] and it is a list of numeric values.但是我收到错误“hist.default(num_data[i], main = "hist",breaks = 20, prob = TRUE) 错误:'x' must be numeric ' 我检查了 num_data[i] 的类型和它是一个数值列表。 SO I have no idea of what is the problem.所以我不知道是什么问题。 Can any one please give me hint?任何人都可以给我提示吗?

A side by side ggplot solution.并排的ggplot解决方案。

library(ggplot2)
library(tidyr)
ggplot(gather(num_data, cols, value), aes(x = value)) + 
       geom_histogram(binwidth = 20) + facet_grid(.~cols)

More reliable than hist() is the histogram function from the Hmisc package:比 hist() 更可靠的是来自 Hmisc 包的直方图函数:

library(Hmisc)
hist.data.frame(num_data)

This should print histograms for all columns in your dataframe.这应该打印数据框中所有列的直方图。

Convert the Dataframe in the matrix.转换矩阵中的数据帧。 Suppose that you have data frame file say my data then use the following command:假设您有数据框文件说我的数据,然后使用以下命令:

new_data=data.matrix(mydata)
hist(new_data)  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM