使用ggplot将数据框中的每一列绘制为一个页面上的直方图 [英] Plot every column in a data frame as a histogram on one page using ggplot

查看:514
本文介绍了使用ggplot将数据框中的每一列绘制为一个页面上的直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个页面上使用直方图绘制data.frame的每一列。这里有一个例子,它使用R中带有的钻石数据集:

  p = list()
对于(i in 1:ncol(diamonds))p [[i]] <-qplot(diamonds [,i],xlab = names(diamonds)[[i]])
do.call(grid。安排,p)


这确实绘制了所有的列,但数据看起来每个都是一样的。所以,有些东西显然是错误的。

这是完成这项任务的正确方法吗?我确定我有一些愚蠢的语法,它将相同的列数据集分配给列表中的每个元素,但我不确定它是什么。



谢谢

解决方案

在这里你可以:

 < (d,aes(x = 1))(code $> library(reshape2)
library(ggplot2)
d < - melt(diamonds [, - c(2:4)])
ggplot值))+
facet_wrap(〜variable,scales =free_x)+
geom_histogram()



fusion ing允许我们使用结果分组变量(称为变量)将数据拆分成组并绘制一个每一个的直方图。请注意使用 scales =free_x,因为每个变量的范围和比例都有明显的不同。


I would like to plot each column of a data.frame using a histogram on one page. Here is an example using the sample "diamonds" data set which comes with R:

p = list()
for (i in 1:ncol(diamonds)) p[[i]] <- qplot(diamonds[,i], xlab=names(diamonds)[[i]])
do.call(grid.arrange, p)

This does plot all the columns, but the data looks the same in each one. So, something is clearly wrong.

Is this the right approach for this task? I'm sure I have some silly syntax somewhere that is assigning the same column data set to each element in the list, but I'm not sure what it is.

Thank you

解决方案

Here you go:

library(reshape2)
library(ggplot2)
d <- melt(diamonds[,-c(2:4)])
ggplot(d,aes(x = value)) + 
    facet_wrap(~variable,scales = "free_x") + 
    geom_histogram()

melting allows us to use the resulting grouping variables (called variable) to split the data into groups and plot a histogram for each one. Note the use of scales = "free_x" because each of the variables has a markedly different range and scale.

这篇关于使用ggplot将数据框中的每一列绘制为一个页面上的直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆