![](/img/trans.png)
[英]How to prepare data to create a grouped histogram from 2 columns of a data frame
[英]how create histogram from data frame in R
我想從數據框創建直方圖,但每次使用代碼時,我都會收到錯誤'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()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.