Home > Mobile >  ggplot the increment over years
ggplot the increment over years

Time:02-28

Recently started learning ggplots but I am far from experienced yet. I have the head of a data frame here to demonstrate the data, and I want to plot the increment of changes in different species over year.

         Category Year Mammals Birds Reptiles Amphibians Fishes Insects Molluscs
3 Endangered (EN) 2019     505   461      565        964    868     571      564
4 Endangered (EN) 2018     482   469      515        903    674     537      546
5 Endangered (EN) 2017     476   461      484        869    676     461      547
6 Endangered (EN) 2016     464   448      421        852    660     408      513
7 Endangered (EN) 2015     481   416      361        810    614     305      503
8 Endangered (EN) 2014     477   419      356        789    587     270      501
  Other invertebrates Plants Fungi & protists
3                 344   5727               60
4                 348   4537               21
5                 340   4123               18
6                 312   3691               12
7                 311   3510               11
8                 307   3231                1

The desired product is from ggplot as below with each line representing one species (Category has two values: Endangered and Vulnerable). How can I do this? Thanks first!

enter image description here

CodePudding user response:

You need to transform your dataset from wide to long. I tried to reproduce your problem so here is my code:

# Example dataset
df <- data.frame(Category = c("Endangered", "Endangered", "Endangered", "Endangered", "Endangered", "Vulnerable", "Vulnerable", "Vulnerable", "Vulnerable", "Vulnerable"),
                 Year = c(2019, 2018, 2017, 2016, 2015, 2019, 2018, 2017, 2016, 2015),
                 Birds = c(123, 430, 550, 666, 444, 111, 272, 363, 466, 787),
                 Plants = c(123, 450, 550, 666, 444, 211, 222, 353, 466, 707),
                 Fishes = c(323, 230, 560, 616, 444, 111, 222, 23, 466, 87))
# Transform dataset from wide to longer
df_long <- gather(df, condition, measurement, Birds:Fishes, factor_key=TRUE)

# plot
df_long %>% ggplot(aes(x = Year, y = measurement, color = condition))   
  geom_line()  
  facet_wrap(~Category)
  • Related