如何使用ggplot2绘制匹配数据的行

时间:2017-04-20 19:48:12

标签: r ggplot2 dplyr

plot increase_rate包含abs(increase_rate) > 0.05
但在代码下,丢弃-0.05到0.05之间的数据。

我还绘制了从-0.05到0.05范围的数据。

library(tidyverse)
data(population, package="tidyr")

population %>%
  arrange(country, year) %>%
  group_by(country) %>%
  mutate(population_nextY = lead(population)) %>%
  mutate(increase_rate = (population_nextY - population)/population_nextY) %>%
  filter(abs(increase_rate) > 0.05) %>%
  ungroup %>%
  ggplot()+
  geom_line(aes(x = year, y = increase_rate, color = country)) 

我想得到这样的最终情节。enter image description here

d <- 
  population %>%
  arrange(country, year) %>%
  group_by(country) %>%
  mutate(population_nextY = lead(population)) %>%
  mutate(increase_rate = (population_nextY - population)/population_nextY) %>%
  ungroup

select_country <- 
  d %>% filter(!between(increase_rate, -0.05, 0.05)) %>%
  select(country) %>% distinct %>% unlist

d %>%
  filter(country %in% select_country) %>%
  ggplot()+
  geom_line(aes(x = year, y = increase_rate, color = country))

2 个答案:

答案 0 :(得分:0)

使用between

filter(!between(increase_rate, -0.05, 0.05))

答案 1 :(得分:0)

使用mutate()函数添加列

population %>%
  arrange(country, year) %>%
  group_by(country) %>%
  mutate(population_nextY = lead(population)) %>%
  mutate(increase_rate = (population_nextY - population)/population_nextY) %>%
  mutate(judge = max(abs(increase_rate), na.rm=T)) %>%
  filter(judge > 0.05) %>%
  ungroup %>%
  ggplot() + 
  geom_line(aes(x = year, y = increase_rate, color = country))