Home > OS >  Gradient-color a line in ggplot2 R
Gradient-color a line in ggplot2 R

Time:11-26

I currently have this plot

enter image description here

with this data

# A tibble: 2 × 7
  `Country Name` `Country Code` Year  `CrecimientoPBI (%)` `Inflación (%)` `Desempleo (%)` Code 
  <chr>          <chr>          <chr>                <dbl>           <dbl>           <dbl> <chr>
1 Estados Unidos USA            1961                  2.3             1.07            6.7  us   
2 Estados Unidos USA            2020                 -3.49            1.23            8.05 us 

I want to color the line that unites the two points in a gradient form, going from the gold color of 1961 to the dark green of 2020. Is there a way to do that? Thanks in advance!

CodePudding user response:

One option to achieve that would be via ggforce::geom_link2:

library(ggforce)
#> Loading required package: ggplot2

d <- tibble::tibble(
  `Country Name` = c('Estados Unidos', 'Estados Unidos'),
  `Country Code` = c('USA', 'USA'),
  Year = c(1961, 2020),
  `CrecimientoPBI (%)` = c(2.3, -3.49),
  `Inflación (%)` = c(1.07, 1.23),
  `Desempleo (%)` = c(6.7, 8.05)
)

ggplot(d, aes(x = `Inflación (%)`, y = `Desempleo (%)`, color = factor(Year)))  
  geom_point(aes(size = `CrecimientoPBI (%)`))   
  geom_link2(aes(group = 1))  
  scale_color_manual(values = c(`1961` = "gold", `2020` = "darkgreen"))  
  theme_minimal()  
  guides(size = "none")

  • Related