[R] Plotting a graph for every Level of a Factor
hadley wickham
h.wickham at gmail.com
Thu Jan 8 01:25:49 CET 2009
On Wed, Jan 7, 2009 at 5:10 PM, jimdare <jamesdare26 at gmail.com> wrote:
>
> Hello,
>
> Using the dataset below, is there a way to generate a bar/line plot for the
> TACC/Catch of every lvl of stock? i.e. OR1,OR3,OR5. The picture at the
> bottom of this post is an example of the bar/line plot for OR1 which was
> generated when OR1 was the only stock in the table. This was created, with
> help from Marc Schwartz, using:
>
>> mp <- barplot(fish$TACC, space = 0, names.arg = fish$Year,ylim=c(0,13000))
>> lines(mp, fish$Catch, type = "b", pch = 19)
>
> Is there a way to instruct R to plot this for one particular stock from the
> table below, and, if so, is there a way to automate it so it plots a figure
> for each individual stock.
It's not terribly easy to see exactly what you are trying to do (why
the combination of bars and lines?) but maybe this is close to what
you want:
install.packages("ggplot2")
library(ggplot2)
fish <- read.table(textConnection("Year Species Stock TACC Catch
2001 ORH OR1 5000 4687
2002 ORH OR1 6000 3215
2003 ORH OR1 7000 6782
2004 ORH OR1 9000 10000
2005 ORH OR1 9000 12000
2001 ORH OR3 20000 7892
2002 ORH OR3 25000 27000
2003 ORH OR3 30000 32000
2004 ORH OR3 30000 29000
2005 ORH OR3 30000 30000
2001 ORH OR5 23000 10982
2002 ORH OR5 23000 24590
2003 ORH OR5 23000 24035
2004 ORH OR5 25000 29008
2005 ORH OR5 20000 21092"), header=T)
ggplot(fish, aes(x = Year)) +
geom_line(aes(y = Catch, colour = "Catch")) +
geom_line(aes(y = TACC, colour = "TACC")) +
facet_grid(Species ~ Stock) +
labs(colour = "??")
# or if you really want bars
ggplot(fish, aes(x = Year)) +
geom_bar(aes(y = TACC), stat = "identity", fill = "grey70") +
geom_line(aes(y = Catch)) +
geom_point(aes(y = Catch)) +
facet_grid(Species ~ Stock)
# this will split up by species too, but you only have one species
# in your example dataset
Hadley
--
http://had.co.nz/
More information about the R-help
mailing list