I'm trying to plot this dataset with ggplot2, putting the name of each country in each line geom_line() and with the x axis (Year) and the y axis (with the relevant data from each country).
            Asked
            
        
        
            Active
            
        
            Viewed 309 times
        
    2 Answers
1
            
            
        You kind of answered your question. You require the package reshape to bring all countries into a single column.
    Year<-c(1991,1992,1993,1994,1995,1996)
Argentina<-c(235,531,3251,3153,13851,16513)
Mexico<-c(16503,16035,3516,3155,30351,16513)
Japan<-c(1651,868416,68165,35135,03,136816)
df<-data.frame(Year,Argentina,Mexico,Japan)
library(reshape2)
df2<- melt(data = df, id.vars = "Year", Cont.Val=c("Argentina","Mexico","Japan"))
library(ggplot2)
ggplot(df2, aes(x=Year, y=value, group=variable, color=variable))+
  geom_line()
 
    
    
        Ginko-Mitten
        
- 304
- 1
- 11
0
            If you want to use ggplot you should bring your data into a "longer" format. Using package tidyr:
df %<>%
  pivot_longer(cols=matches("[^Year]"),
               names_to="Country", 
               values_to="Value")
gives you
# A tibble: 108 x 3
    Year Country       Value
   <dbl> <chr>         <dbl>
 1  1995 Argentina   4122262
 2  1995 Bolivia     3409890
 3  1995 Brazil     36276255
 4  1995 Chile       2222563
 5  1995 Colombia   10279222
 6  1995 Costa_Rica  1611055
 7  1997 Argentina   4100563
 8  1997 Bolivia     3391943
 9  1997 Brazil     35718095
10  1997 Chile       2208382
Based on this it is easy to plot a line for each country using ggplot2:
ggplot(df, aes(x=Year, y=Value, color=Country)) + 
  geom_line()
 
    
    
        Martin Gal
        
- 16,640
- 5
- 21
- 39
