Home > Net >  How to rearrange dataset for ScatterPlot using ggplot in R
How to rearrange dataset for ScatterPlot using ggplot in R

Time:05-02

I'm trying to plot the countries current co2 emissions over the 6 years but I'm having trouble with the way the data is entered in the excel file. I tried using unlisting and tried combining new vars but with no luck. Any help on determining aes(x =, y=) for the data sets I provided?

structure(list(`2010` = c(5.78, 7.34, 8.74, 1.45, 17.9), `2011` = c(5.76, 
7.56, 8.49, 1.56, 17.1), `2012` = c(5.75, 7.36, 7.62, 1.56, 17.5
), `2013` = c(5.23, 6.71, 7.36, 1.7, 17.5), `2014` = c(5.3, 6.42, 
7.04, 1.76, 16.9), `2015` = c(5.31, 6.04, 6.73, 1.79, 16.4)), row.names = c(59L, 
62L, 69L, 79L, 184L), class = "data.frame")

CodePudding user response:

Assuming each row is a different country:

library(tidyverse)
j_df <- structure(list(
  `2010` = c(5.78, 7.34, 8.74, 1.45, 17.9),
  `2011` = c(5.76,  7.56, 8.49, 1.56, 17.1),
  `2012` = c(5.75, 7.36, 7.62, 1.56, 17.5 ),
  `2013` = c(5.23, 6.71, 7.36, 1.7, 17.5),
  `2014` = c(5.3, 6.42,  7.04, 1.76, 16.9),
  `2015` = c(5.31, 6.04, 6.73, 1.79, 16.4)
), row.names = c(59L,  62L, 69L, 79L, 184L), class = "data.frame") 

j_df %>%
  rownames_to_column(var = "rowname") %>% 
  rename(Country = rowname) %>%
  pivot_longer(cols = `2010`:`2015`, names_to = "year", values_to = "C_Emissions") %>% 
  ggplot(aes(x = year, y = C_Emissions, color = Country))  
  geom_point()  
  geom_line(aes(group = Country))

  •  Tags:  
  • r
  • Related