Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bar plot for count data by group in R

Tags:

plot

r

I'm trying to create a bar plot in R, similar to the one in this question. If possible, I would prefer to not use ggplot - although I use it frequently, this is just a small line of a stats tutorial I'm creating and I'd rather not get everyone to install more packages than is critical.

This is a portion of the data frame I'm working with:

    Site Depth Substrate PoePres HaliPres Species
1      2   0.5      Sand       0        1  DMonte
2      2   0.5      Sand       0        1  DMonte
3      2   0.5      Sand       0        1  DMonte
4      2   0.5      Sand       0        1  DMonte
5      2   0.5      Sand       0        1  DMonte
6      2   0.5      Sand       0        1  DSandi
7      2   0.5      Sand       0        1  DSandi
8      2   0.5      Sand       0        1  DSandi
9      7   0.6      Sand       0        1  DMonte
10     7   0.6      Sand       0        1  DMonte
11     7   0.6      Sand       0        1  DMonte

There are 130 observations, with three levels for Species and depth ranging up to 40 feet. I would like to create a bar chart, just to be able to visualize the data, with depth along the x axis and count on the y axis, so that for every foot of depth, the total count for each species is plotted side by side (referring to the linked question, my Depth would be their proc, and my Species would be Rtime/Btime).

I've tried using barplot, hist, histogram, and even ggplot, all with a variety of errors. There is clearly something I'm not grasping, but several hours of internet searching and experimentation have not gotten me very far!

I would appreciate any help anyone could provide.

like image 948
Victoria Avatar asked Mar 31 '15 14:03

Victoria


1 Answers

Before you can use functions like barplot, you need to format the data properly. Look at ?table. If mydata is your dataframe:

tbl <- with(mydata, table(Species, Depth))

barplot(tbl, beside = TRUE, legend = TRUE)

enter image description here

Or using ggplot:

library(ggplot2)
ggplot(as.data.frame(tbl), aes(factor(Depth), Freq, fill = Species)) +     
  geom_col(position = 'dodge')

enter image description here

like image 140
Axeman Avatar answered Oct 18 '22 19:10

Axeman