Home > Back-end >  ggplotting multiple lines of same data type on one line graph
ggplotting multiple lines of same data type on one line graph

Time:09-03

So i have this data, that I would like to plot onto a graph - all the lines on the same graph

>ndiveristy
 Quadrant nta.shannon ntb.shannon ntc.shannon
1        1    2.188984   0.9767274   1.8206140
2        2    1.206955   1.3240481   1.3007058
3        3    1.511083   0.5805081   0.7747041
4        4    1.282976   1.4222243   0.4843907
5        5    1.943930   1.7337267   1.5736545
6        6    2.030524   1.8604619   1.6860711
7        7    2.043356   1.5707110   1.5957869
8        8    1.421275   1.4363365   1.5456799

here is the code that I am using to try to plot it:

ggplot(ndiversity,aes(x=Quadrant,y=Diversity,colour=Transect)) 
       geom_point() 
       geom_line(aes(y=nta.shannon),colour="red") 
       geom_line(aes(y=ntb.shannon),colour="blue") 
       geom_line(aes(y=ntc.shannon),colour="green")

But all I am getting is the error

data must be a data frame, or other object coercible by fortify(), not a numeric vector.

Can someone tell me what I'm doing wrong

CodePudding user response:

Typically, rather than using multiple geom_line calls, we would only have a single call, by pivoting your data into long format. This would create a data frame of three columns: one for Quadrant, one containing labels nta.shannon, ntb.shannon and ntc.shannon, and a column for the actual values. This allows a single geom_line call, with the label column mapped to the color aesthetic, which automatically creates an instructive legend for your plot too.

library(tidyverse)

as.data.frame(ndiversity) %>%
  pivot_longer(-1, names_to = 'Type', values_to = 'Shannon') %>%
  mutate(Type = substr(Type, 1, 3)) %>%
  ggplot(aes(Quadrant, Shannon, color = Type))   
  geom_line(size = 1.5)  
  theme_minimal(base_size = 16)  
  scale_color_brewer(palette = 'Set1')

enter image description here

CodePudding user response:

For posterity:

  1. convert to data frame
ndiversity <- as.data.frame(ndiversity)
  1. get rid of the excess code
ggplot(ndiversity,aes(x=Quadrant)) 
                     geom_line(aes(y=nta.shannon),colour="red") 
                     geom_line(aes(y=ntb.shannon),colour="blue") 
                     geom_line(aes(y=ntc.shannon),colour="green")
  1. profit

not the prettiest graph I ever made

  • Related