# plot histogram in r

#### Jesmin

##### New Member
I have the following data set:

$$\begin{tabular}{|l c r|} \hline X & Y & Type \\ \hline 32 & 48.5 & A \\ 36.3 & 42.9 & A \\ 45.8 & 75.8 & A \\ 60.5 & 5457.6 & B \\ 12 & 6666 & B \\ 24.2 & 48.5 & C \\ 271 & 2796.6 & C \\ \hline \end{tabular}$$

Now I have to draw histogram of the variable Y by the variable Type.

Code:
data <- data.frame(X=c(32,36.3,45.8,60.5,12,24.2,271),
Y=c(48.5,42.9,75.8,5457.6,6666,48.5,2796.6),
Type=c("A","A","A","B","B","C","C"))
data

with(data, hist(Type~Y) )
Error in hist.default(Type ~ Y) : 'x' must be numeric
>

#### bryangoodrich

##### Probably A Mammal
First, read the documentation. The hist function has no formula specification. Even if it did, it is almost always immediately followed by the data set, so your use of with would be unnecessary. For example

Code:
lm(Y ~ Type, data = data)
Histograms don't overlay (do you want a barchart? Very different), so you'd have to have 3 different histograms, one for each Type.

Code:
par(mfrow = c(1, 3))  # Set up your graphic device for 1 row of 3 columns to plot your histograms
with(data, tapply(Y, Type, hist))
It's ugly, but it'll plot what you want with that data.

If you want to plot your bars with associated coloring to identify the Types, you could do something like this

Code:
with(data, barplot(Y, col = Type))