我想從數據幀創建直方圖,但每次使用代碼時都會得到錯誤'x' must be numeric
。如何從數據幀中創建直方圖R
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)
我想從數據幀創建直方圖,但每次使用代碼時都會得到錯誤'x' must be numeric
。如何從數據幀中創建直方圖R
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)
我建議使用ggplot庫 這裏有一個例子
generateHistogram <- function(columnName) {
#I used library(ggplot2)
houseDFPlot <- ggplot(data=DF, aes(x=DF[columnName]))
#layering
houseDFPlot + geom_histogram()
}
請考慮其他可視化你的例子,作爲直方圖未必是最適合的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))
或boxplot:
ggplot(df_tidy, aes(x = cols, y=value)) +
geom_boxplot(aes(fill=cols))
'df $ col1'和'df $ col2'是數字。 – jogo
您不能在數據框外創建直方圖。基'hist'函數期望數字向量(即來自數據幀的列)。 'ggplot'可以處理數據幀,但是無論如何將會使用來自一列的值(儘管它可能使用另一列來進行分組)。 –