在 R 中使用 ggplot 绘制直方图矩阵

use*_*934 3 r histogram ggplot2

我是 R 的新手,一直在尝试使用“态度”数据集为每一列创建直方图。

我可以通过输入以下内容手动实现此目的:

par(mfrow=c(1,7)) hist(attitude$rating) hist(attitude$complaints) hist(attitude$privileges) hist(attitude$learning) hist(attitude$raises) hist(attitude$critical) hist(attitude$advance)

However, what I'd like to do is use a single function to plot all the histograms, possibly using ggplot. This is the command I used after searching on Stackoverflow:

ggplot(attitude, aes(x=variable)) + geom_histogram()

but it seems I'm doing it wrong since I get this message:

Error in eval(expr, envir, enclos) : object 'variable' not found

I will appreciate any pointers in this regard. Thank you.

CMi*_*ael 5

您需要首先将态度数据转换为长数据格式 - 例如,通过使用meltfrom reshape2

attitudeM <- melt(attitude)
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过变量对 ggplot 进行分面,并自动为每个维度创建单独的直方图。

g <- ggplot(attitudeM,aes(x=value))
g <- g + geom_histogram()
g <- g + facet_wrap(~variable)
g
Run Code Online (Sandbox Code Playgroud)