如何在R中从数据框创建直方图

6

我想从数据框中创建直方图,但每次使用代码时都会出现错误'x' must be numeric

    df <- data.frame(col1 = c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120),
    col2 = c(10, 21, 31, 41, 51, 61, 72, 82, 92, 104, 114, 134))

    hist(df)

df$col1df$col2 是数值型的。 - jogo
你不能从数据框中创建直方图。基础的hist函数期望一个数值向量(即来自数据框的列)。ggplot可以使用数据框,但是无论如何都只会使用一列的值(尽管它可能会使用另一列进行分组)。 - Mirek Długosz
4个回答

5

你可以做:

hist(df$col1)

或者

with(df, hist(col2))

如果您想要每个列都在自己的直方图中,您可以尝试这样做:
par(mfrow=c(2,1))
histout=apply(df,2,hist)

4

请考虑其他可视化方式,因为直方图可能不适合用于比较col1和col2中非常相似的数据。 在您的情况下,首先将df转换为整洁的格式会很有用。

library(ggplot2)
library(tidyr)

df_tidy <- gather(df, cols, value) 

然后使用以下图表之一来突出数据中的小差异:

作为密度图:

ggplot(df_tidy, aes(x = value)) + 
  geom_density(aes(color=cols))

或散点图:

ggplot(df_tidy, aes(x = value, y=cols)) + 
  geom_point(aes(color=cols), size=3) +
  scale_x_continuous(breaks = c(0,25,50,75,100,125))

或者箱线图:
ggplot(df_tidy, aes(x = cols, y=value)) + 
  geom_boxplot(aes(fill=cols))

1
如果您想要所有数据的直方图,可以使用
hist(c(df$col1,df$col2))

0

我建议使用ggplot库,这里有一个例子

generateHistogram  <- function(columnName) {
  #I used library(ggplot2)
  houseDFPlot <- ggplot(data=DF, aes(x=DF[columnName]))
  #layering
  houseDFPlot + geom_histogram()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接