Jane Miller
Jane Miller

Reputation: 153

How to plot multiple histograms at once of specific columns within dataset R

I am using the R dataset "USArrests" and am trying to plot the histograms of each column. However, when I do this, I am not able to figure out how to put the xaxis label as well as the title for each histogram labeling the variable that I am looking at.

I currently have

attach(USArrests)
lapply(arrests[,c(1:4)], FUN = hist)

The four histograms outputted look like this: Histogram of Murder

How can I add the axis/title labels? Thanks

Upvotes: 0

Views: 1607

Answers (1)

neilfws
neilfws

Reputation: 33782

If you want to use base R, this is an occasion where a for-loop is better than lapply.

par(mfrow = c(2, 2))
for(i in names(USArrests))
  hist(USArrests[[i]], main = i, xlab = "Value")

enter image description here

You could also use tidyr and ggplot2 with facets, but would need to experiment with the histogram bin size.

library(tidyr)
library(ggplot2)

USArrests %>% 
  pivot_longer(cols = 1:4) %>% 
  ggplot(aes(value)) + 
  geom_histogram() + 
  facet_wrap(~name, scales = "free")

enter image description here

Upvotes: 3

Related Questions