我想从数据框中创建直方图,但每次使用代码时都会出现错误'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)
你可以做:
hist(df$col1)
或者
with(df, hist(col2))
par(mfrow=c(2,1))
histout=apply(df,2,hist)
请考虑其他可视化方式,因为直方图可能不适合用于比较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))
hist(c(df$col1,df$col2))
我建议使用ggplot库,这里有一个例子
generateHistogram <- function(columnName) {
#I used library(ggplot2)
houseDFPlot <- ggplot(data=DF, aes(x=DF[columnName]))
#layering
houseDFPlot + geom_histogram()
}
df$col1
和df$col2
是数值型的。 - jogohist
函数期望一个数值向量(即来自数据框的列)。ggplot
可以使用数据框,但是无论如何都只会使用一列的值(尽管它可能会使用另一列进行分组)。 - Mirek Długosz