Home > Software engineering >  Color time-series with numeric variables
Color time-series with numeric variables

Time:11-25

I'm making a time-series plot on two economic variables: inflation and PBI growth.

My data looks like this:

# A tibble: 6 × 6
  `Country Name` `Country Code` Year  `CrecimientoPBI (%)` `Inflación (%)` `Desempleo (%)`
  <chr>          <chr>          <chr>                <dbl>           <dbl>           <dbl>
1 Estados Unidos USA            1961                   2.3            1.07             6.7
2 Estados Unidos USA            1962                   6.1            1.2              5.5
3 Estados Unidos USA            1963                   4.4            1.24             5.7
4 Estados Unidos USA            1964                   5.8            1.28             5.2
5 Estados Unidos USA            1965                   6.4            1.59             4.5
6 Estados Unidos USA            1966                   6.5            3.02             3.8

I want to add a legend saying which color corresponds to each variable, but given they are numerical variables I can't do it. When I do it like "aes(col = as.factor(...))" it doesn't work either, I just get ll the numerical observations.

To sum up, this is what I currently have:

Plot

And I want to add a legend with a red line saying "PBI Growth" and a blue line saying "Inflation".

Anybody know how to do it proper? Thanks in advance.

CodePudding user response:

Your best bet will be to pivot your data first, so you can pass the series type as an aesthetic.

It seems you also have two line types there, so I've included something like that in the reprex below.

library(tidyverse)

mydat <- 
  read_table("
CountryName CountryCode        Year         CrecimientoPBI       Inflación       Desempleo
Estados Unidos  USA            1961                   2.3            1.07             6.7
Estados Unidos  USA            1962                   6.1            1.2              5.5
Estados Unidos  USA            1963                   4.4            1.24             5.7
Estados Unidos  USA            1964                   5.8            1.28             5.2
Estados Unidos  USA            1965                   6.4            1.59             4.5
Estados Unidos  USA            1966                   6.5            3.02             3.8")

mydat %>% 
  select(Year, CrecimientoPBI, Inflación, Desempleo) %>% 
  pivot_longer(cols = c(CrecimientoPBI, Inflación, Desempleo)) %>% 
  mutate(type = if_else(name == "Desempleo", "labor-related", "growth-related")) %>% 
  ggplot()   
  geom_line(aes(x = Year, y = value, color= name, linetype = type))   
  geom_point(aes(x = Year, y = value, color= name), size = 2, alpha = 0.4)   
  theme_classic()  
  theme(legend.position = "right")

Created on 2021-11-23 by the reprex package (v2.0.1)

  • Related