0

I have a dataframe with 8 columns (8 variables) and 1000's of observations. I would like to plot a histogram and a boxplot for each variable in the same panel.

For example

h1 h2 h3 h4

b1 b2 b3 b4

h5 h6 h7 h8

b5 b6 b7 b8

where hn= histogram of variable n. and bn= boxplot of variable n.

I tried boxplot(dataframe)

hist(dataframe)

But the boxplots are located in the same chart and I get the following error for the histogram:

Error in hist.default(dataframe) = 'x' must be numeric

Thanks in advance!

pd. is it possible to add a color palette to this panel?

rwn1v
  • 777
  • 3
  • 10
  • 23

2 Answers2

0

I'd recommend simply writing a little loop to pick out one column at a time and plot it. You'll want to fine-tune this, but it should be enough to get you started:

par(mfrow = c(8,2))
for(i = 1:8){
  hist(dataframe[,i])
  boxplot(dataframe[,i])
}
zkurtz
  • 3,230
  • 7
  • 28
  • 64
0

The error you get from hist(dataframe) is because hist needs to be fed with a "a vector of values". See description of the x in ?hist). boxplot on the other hand accepts "Either a numeric vector, or a single list containing such vectors". Because a data frame is a list, hist will accept df.

Because you wish to have all your plots on the "same panel", you will need to arrange your them on your plotting device, using e.g. par(mfrow = (see ?par).

There are some previous posts showing how to combine a single histogram with a boxplot (this and this). Here is yet another possibility using histBxp from package sfsmisc.

library(sfsmisc)

# Some dummy data
df <- data.frame(matrix(rnorm(200), ncol = 8))

# arrange plots in two rows and four columns
par(mfrow = c(2,4)) 

# create a palette to pick colours from (see `palette`), e.g:
mycols <- rainbow(n = 8)

# 'loop' over columns in df using lapply, and make a "histBxp" for each column.
lapply(1:8, function(i) histBxp(df[ , i], main = "", xlab = i,
                            col = mycols[i],
                            boxcol = mycols[i],
                            medcol = 1))
Community
  • 1
  • 1
Henrik
  • 65,555
  • 14
  • 143
  • 159