Karen H
Karen H

Reputation: 43

Multiple histograms with title and mean as a line?

I'm struggeling with the histogram function in my exploratory analysis. I would like to run a couple of variables in my dataset through a histogram function and for each add the title and a line at the arithmetic mean. This is how far I've got (but the main title is still missing):

histo.abline <-function(x){

  hist(x)

  abline(v = mean(x, na.rm = TRUE), col = "blue", lwd = 4)}

sapply(dataset[c(7:10)], histo.abline)

I tried to add a main argument in the histogram function but it just doesn't pick the right variable name of my dataset vector. When I put main=x there, it says returns NULL for each variable. Colnames, names and other functions didn't work either. Could you help me?

Upvotes: 1

Views: 1004

Answers (1)

Antonios
Antonios

Reputation: 1939

you can try to do it with ggplot:

library(ggplot)
histo.abline <-function(dataset,colnum){
  p<-ggplot(dataset,aes(dataset[,colnum]))+geom_histogram(bins=5,fill=I("blue"),col=I("red"), alpha=I(.2))+
    geom_vline(xintercept = mean(dataset[,colnum], na.rm = TRUE))+xlab(as.character(names(dataset)[colnum]))
  return(p)
}

since you have not provided data lets work with mtcars and create a list of histograms

dataset=mtcars
listOfHistograms<-lapply(3:7,function(x) histo.abline(dataset,x))

your list has 5 histograms that you can plot for instance the first by:

print(listOfHistograms[[1]])

enter image description here

More histogram options for ggplot here: https://www.r-bloggers.com/how-to-make-a-histogram-with-ggplot2/

hope this helps

EDIT: Multiple Plot in one graph

One way to do it is through cowplot library:

library(cowplot)
plot_grid(plotlist=listOfHistograms[1:4])

enter image description here

Upvotes: 1

Related Questions