Reputation: 153
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:
How can I add the axis/title labels? Thanks
Upvotes: 0
Views: 1607
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")
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")
Upvotes: 3