From tidytuesday datasets I am trying to create a line plot which color in blue if greater than 0 and red if less than 0.
library(tidyverse)
library(tidytuesdayR)
library(ggthemes)
library(glue)
library(scales)
Loading data
tt <- tt_load("2021-02-23")
employed <- tt$employed
Plot
employed %>%
na.omit() %>%
group_by(year) %>%
summarise(employment_yrwise = sum(employ_n)) %>%
mutate(employ_change = (employment_yrwise - lag(employment_yrwise, default = 0))/
lag(employment_yrwise) ) %>%
mutate(employ_change = replace(employ_change, is.na(employ_change), 0),
line_color = ifelse(employ_change >= 0, "blue","red")) %>%
ggplot(aes(x = year, y = employ_change,
label = round(employ_change*100, digits = 2),
col = line_color)) +
geom_line(group=1) +
geom_point() +
scale_y_continuous(labels = scales::percent_format(),
limits = c(-0.08, 0.02) ) +
geom_text(nudge_y = .005) +
labs(title = "Yearly % Change in Employment")
I am not sure why am I getting below chart by above code which seems to be reverse in colors and line doesn't color properly when it falls below 0:
Also tried below code but that didn't work either:
employed %>%
na.omit() %>%
group_by(year) %>%
summarise(employment_yrwise = sum(employ_n)) %>%
mutate(employ_change = (employment_yrwise - lag(employment_yrwise, default = 0))/
lag(employment_yrwise) ) %>%
mutate(employ_change = replace(employ_change, is.na(employ_change), 0) #,
#line_color = ifelse(employ_change >= 0, "blue","red")
) %>%
ggplot(aes(x = year, y = employ_change,
label = round(employ_change*100, digits = 2)
# ,col = line_color
)) +
geom_line(group=1) +
geom_point() +
scale_y_continuous(labels = scales::percent_format(),
limits = c(-0.08, 0.02) ) +
scale_color_manual(values = c("blue","red")) +
geom_text(nudge_y = .005) +
labs(title = "Yearly % Change in Employment")