How to remove "almost flat" trend lines?

Viewed 69

My code is:

library(dplyr)
library(ggplot2)
library(pwt10)

p1 <- pwt10.0 %>% 
    mutate(my_color = ifelse(isocode == "KOR","Korea", "Other")) %>% 
    ggplot(aes(year, labsh, group = isocode, color = my_color))+
    geom_line() +
    scale_color_manual(values = c("black", "grey", "white"))+
    xlim(1980,1997)

p1

And it turns out as:

enter image description here

I was wondering if there's a way to remove all "almost flat" grey lines and make the black line stand out (currently it is covered by other grey lines).

1 Answers

The following code will put the blackline on top.

p1 <- pwt10.0 %>% 
    select(year, labsh, isocode) %>% 
    mutate(my_color = ifelse(isocode == "KOR", "Korea", "Other")) %>%
    na.omit() %>%
    ggplot(aes(year, labsh, group = isocode, color = my_color)) +
    geom_line(data = . %>% filter(isocode != "KOR")) +
    geom_line(data = . %>% filter(isocode == "KOR")) +
    scale_color_manual(values = c("black", "grey")) +
    labs(color = "Country") +
    xlim(1980,1997)

p1

As for the flat lines, they are almost flat, but only 3 are horizontal:

pwt10.0 %>%
    select(year, labsh, isocode) %>% 
    na.omit() %>%
    group_by(isocode) %>%
    summarise(flat = diff(range(labsh)),
              flat = isTRUE(all.equal(flat, 0))) %>%
    filter(flat)
## A tibble: 3 x 2
#  isocode flat 
#  <fct>   <lgl>
#1 LBN     TRUE 
#2 STP     TRUE 
#3 TGO     TRUE 

Following a comment, the code below removes the flat lines.

p2 <- pwt10.0 %>% 
    select(year, labsh, isocode) %>% 
    na.omit() %>%
    group_by(isocode) %>%
    mutate(slope = diff(range(labsh, na.rm = TRUE)),
           flat = isTRUE(all.equal(slope, 0))) %>%
    filter(!flat) %>%
    filter(abs(slope) >= 0.15) %>%
    select(-flat, -slope) %>%
    ungroup() %>%
    mutate(my_color = ifelse(isocode == "KOR", "Korea", "Other")) %>%
    ggplot(aes(year, labsh, group = isocode, color = my_color)) +
    geom_line(data = . %>% filter(isocode != "KOR")) +
    geom_line(data = . %>% filter(isocode == "KOR")) +
    scale_color_manual(values = c("black", "grey")) +
    labs(color = "Country") +
    xlim(1980,1997)

p2
Related