0
votes

I've been struggling with ggplot in r. I'm trying to create a line graph with three variables plotted onto it - small saplings, medium saplings and large saplings. The X axis will be 'mean number of saplings' and the Y axis should be 'bird species richness'.

Here is an extract:

birdspp smallsaplings   mediumsaplings  largesaplings
95      5.044642857     2.384615385     1.30952381
97      3.482269504     1.873684211     1.390625
63      6.285714286     2               2.4
57      5.216216216     1.666666667     1.125

My problem is, I can't for the life of me work out how to plot all three lines on one graph!

I have tried two approaches. The traditional hopeful way...

 ggplot(data, aes(y=birdspp, x=saplings)) + 
  geom_line(aes(x = smallsaplings, colour = "blue"))+
  geom_point(aes(x = smallsaplings, colour = "blue")) + 
  geom_line(aes(x = mediumsaplings, colour = "green")) +
  geom_point(aes(x = mediumsaplings, colour = "green")) + 
  geom_line(aes(x = largesaplings, colour = "red")) +
  geom_point(aes(x = largesaplings, colour = "red")) 

which produces this monstrosity :(

and using a melt function from the reshape library...

mdf <- melt(mdf, id.vars="Sapplings", value.name="value", variable.name="birdspp")
ggplot(data=mdf, aes(x=Sapplings, y=value, group = birdspp, colour = birdspp)) +
    geom_line() +
    geom_point( size=4, shape=21, fill="white")

Apologies if the error is blindingly obvious, I'm a newbie.

1
One issue is x=saplings in your main call to ggplot. This column doesn't exist in your data. Also the plot will be much easier if you convert you data to "long" format. Something like this: library(reshape2); ggplot(melt(data, id.var="birdspp"), aes(x=value, y=birdspp, colour=variable)) + geom_line() + geom_point(). - eipi10
With your original approach, each line could be plotted similarly to this: ggplot(data, aes(y=birdspp)) + geom_line(aes(x=smallsaplings), colour="blue"). - eipi10
I'm getting close! Graph is here, I am just struggling with the line of best fit. geom_line just links up all the points and ideally I'd want geom_abline but it doesn't seem to be working. - JazTheBilloligist
geom_smooth(method="lm") - eipi10

1 Answers

2
votes

This is a classic "wide to long" problem. It's easier if you tidy the data first, so it has one column with sapling type and another with the mean numbers.

library(dplyr)
library(tidyr)

df1 %>% 
  gather(sapling_type, mean_number, -birdspp)

Now you can pipe that into ggpplot and colour by sapling type. I'm not sure about lines though. Maybe start with points first.

df1 %>% 
  gather(sapling_type, mean_number, -birdspp) %>% 
  ggplot(aes(mean_number, birdspp)) + geom_point(aes(color = sapling_type))

Result: enter image description here