Trying to make a histogram of all the predictor values in the Glass dataset. I initially used par(mfrow=c(3,3))
to plot all 9 predictors on the same window, but got an error that the margins were too large. That's okay. Writing hist(Glass$X) nine times would've been inefficient anyway.
So then I tried to plot them all at once. I subset the data so that only the numeric columns remained, but got an error saying that they weren't numeric. I've already verified all columns are numeric. What am I doing wrong?
library(mlbench)
data(Glass)
library(lattice)
par(mfrow=c(3,3))
hist(Glass$RI)
> Error in plot.new() : figure margins too large
Glass2=subset(Glass[1:9])
hist(Glass2)
> Error in hist.default(Glass2) : 'x' must be numeric
CodePudding user response:
Here's a tidyverse alternative.
library(tidyr)
library(ggplot2)
Glass %>%
pivot_longer(-Type) %>%
ggplot(aes(value))
geom_histogram()
facet_wrap(~name,
ncol = 3,
scales = "free")
Result:
CodePudding user response:
Subset the data into a new data frame, X. Instead of typing out X$x nine times, use a for loop. Make sure your plot window is really big or you'll get an error that the margins are too small.
X <- Glass[,1:9]
par(mfrow = c(3, 3))
for (i in 1:ncol(X)) {
hist(X[ ,i], xlab = names(X[i]), main = paste(names(X[i]), "Histogram"), col="steelblue")
}