【问题标题】:how to plot lines matching data using ggplot2如何使用ggplot2绘制匹配数据的线
【发布时间】:2017-04-20 19:48:11
【问题描述】:

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)) 

我想得到这样的最终情节。

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))

【问题讨论】:

    标签: r ggplot2 dplyr


    【解决方案1】:

    使用between:

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

    【讨论】:

    • 我不确定您是要排除 -0.05 到 0.05 之间的数据还是限制在此范围内。如果是后者,删除!
    • 意思是,绘制 abs(increse_rate)>0.05 的国家/地区。
    • 酷,那么上面应该可以工作。如果您遇到任何问题,请告诉我
    • 对不起,我添加了我要提问的细节。
    【解决方案2】:

    使用 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 1970-01-01
      相关资源
      最近更新 更多