0
votes

I am trying to create a connected scatterplot similar to the one and this has more explanation

Essentially, I am trying to show on one graph, the decline in the number of people within the labor force as measured by their numbers. The second graph would show changes in the unemployment rate within the same period.

This is my code:

# ggplot2 call:
Unemployment_Outflows %>%
  ggplot( aes(x=unemployment_rate, y=labor, label=year)) +
  # Custom the Y scales:
  scale_y_continuous() +
geom_line( color="grey") +
    geom_point(shape=21, color="black", fill="#69b3a2", size=3)
  geom_segment(aes(
                    xend=c(tail(unemployment_rate, n=-1), NA), 
                    yend=c(tail(labor, n=-1), NA)
                  )
      ) 

enter image description here However, as you can see, neither the lines nor a shaded area are visible, and I am getting the following error:

"geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?"

year change change_perc unemployment_rate labor

*year (chr) labor unemployment_rate (dbl) (dbl)

Q4 2015 8416681 0 NA
Q4 2016 8492965 12.34717
Q4 2017 7907511 12.83452
Q4 2018 6895514 12.74767
Q4 2019 6437891 12.01787
Q3 2020 6409070 15.44732

1

1 Answers

1
votes

Try adding geom_text(). No output shared as no data was included. Here the code:

library(ggplot2)
library(dplyr)
#Code
Unemployment_Outflows %>%
  ggplot( aes(x=unemployment_rate, y=labor, label=year)) +
  # Custom the Y scales:
  scale_y_continuous() +
  geom_line( color="grey") +
  geom_point(shape=21, color="black", fill="#69b3a2", size=3)
geom_segment(aes(
  xend=c(tail(unemployment_rate, n=-1), NA), 
  yend=c(tail(labor, n=-1), NA)
)
)+geom_text(vjust=0.5,fontface='bold')

Using the data you shared, try this:

library(tidyverse)
#Code
df %>% 
  mutate(year=factor(year,levels = unique(year),ordered = T)) %>%
  pivot_longer(-1) %>%
  ggplot(aes(x=year,y=value,color=name,group=name))+
  geom_point()+geom_line()+geom_area(aes(fill=name),alpha=0.5)+
  facet_wrap(.~name,scales='free',nrow = 1)+
  scale_y_continuous(labels = scales::comma)+
  theme_bw()+
  theme(legend.position = 'top')+
  labs(color='Var',fill='Var')

Output:

enter image description here

Some data used:

#Data
df <- structure(list(year = c("Q4 2015", "Q4 2016", "Q4 2017", "Q4 2018", 
"Q4 2019", "Q3 2020"), labor = c(8416681, 8492965, 7907511, 6895514, 
6437891, 6409070), unemployment_rate = c(0, 12.34717, 12.83452, 
12.74767, 12.01787, 15.44732)), class = "data.frame", row.names = c(NA, 
-6L))