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()
melt
ing 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.
来源:https://stackoverflow.com/questions/13035834/plot-every-column-in-a-data-frame-as-a-histogram-on-one-page-using-ggplot