Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

r - Plot every column in a data frame as a histogram on one page using ggplot

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)

enter image description here

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

enter image description here

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...