如何为时间序列制作分组范围图?

时间:2018-06-15 17:33:44

标签: r ggplot2 reshape

我想在R中渲染温度时间序列的范围图或散点图。基本上,对于每个区域,我需要计算前10年和最后10年'温度平均值和降水总量分别;然后去做一个参考年份的范围情节' gdp_percapita(让我们说1995年的gdp_percapita)与前10年和过去10年相比。温度平均值和降水总量。

可重现的数据

以下是使用实际温度时间序列模拟的可重现数据:

dat= data.frame(index = rep(c('dex111', 'dex112', 'dex113','dex114','dex115'), each = 30), year =1980:2009,
            region= rep(c('Berlin','Stuttgart','Böblingen','Wartburgkreis','Eisenach'), each=30),
            gdp_percapita=rep(sample.int(40, 30), 5),gva_agr_perworker=rep(sample.int(45, 30), 5),
            temperature=rep(sample.int(50, 30), 5), precipitation=rep(sample.int(60, 30), 5))

更新: 这是我到目前为止所做的:

library(tidyverse)
func <- dat %>% 
  group_by(temperature, precipitation) %>% 
  summarize_all(funs(mean, sum))
似乎我错过了前十年和过去十年的平均温度和总降水量。任何更正。

func %>% 
  gather(year, region, temperature, precipitation, gdp_percapita) %>% 
  separate(col, into = c("Measurement", "stat")) %>% 
  arrange(region) %>% 
  mutate_at(vars(col, Measurement), fct_inorder) %>% 
  spread(col, val)

但是上面的代码不适合制作情节,不知道我的代码出了什么问题?有什么想法吗?

我知道ggplot2渲染这些数据的预期范围图是惊人的,但我尝试重塑数据以制作绘图是不正确的。有没有办法在R中制作这个情节?我怎样才能在ggplot2中实现这一目标?有什么想法吗?

更新

不是我为x轴中的所有区域选择2000的gdp_percapita而是为所有区域选择沿y轴的周期性平均温差和降水和差。

所需的情节

这是温度和降水的理想范围图:

expected range plot for temperature

expected range plot for precipitation

如何使用最少的代码高效地完成所需的输出?有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

这是我认为可以满足您需求的解决方案。一般来说,你应该试着让你的问题变得更窄,因为只是说&#34;我不知道出了什么问题&#34;使其他人难以使用这个问题。

这里有几个步骤。我希望将数据转换为每个区域一行的格式,以便与summarise一起绘制,使用它来获取我们需要的美学论据(geom_pointgeom_linerange )。然后,为了绘制两个不同的组,我们gather它们,以便decade可以成为一个组变量。

N.B。我编辑了样本数据,因此它不再让每个组都具有完全相同的数据,只是为了一点点变化。

geom_text_repelggrepel包中的一个很好的功能,可以让标签更容易添加。我们希望仅过滤其中一个组,以便标签不会出现两次。

library(tidyverse)

set.seed(2346)
dat <- data.frame(
  index = rep(c("dex111", "dex112", "dex113", "dex114", "dex115"), each = 30),
  year = 1980:2009,
  region = rep(c("Berlin", "Stuttgart", "Böblingen", "Wartburgkreis", "Eisenach"), each = 30),
  ln_gdp_percapita = sample.int(40, 150, replace = TRUE),
  ln_gva_agr_perworker = sample.int(45, 150, replace = TRUE),
  temperature = sample.int(50, 150, replace = TRUE),
  recipitation = sample.int(60, 150, replace = TRUE)
)

stats <- dat %>%
  group_by(region) %>%
  summarise(
    ln_gdp = mean(ln_gdp_percapita),
    range_max = max(temperature),
    range_min = min(temperature),
    decade_80s = mean(temperature[which(year %in% 1980:1989)]),
    decade_00s = mean(temperature[which(year %in% 2000:2009)])
  ) %>%
  gather(decade, mean, decade_80s, decade_00s)

ggplot(stats, aes(x = ln_gdp)) +
  geom_point(aes(y = mean, colour = decade)) +
  geom_linerange(aes(ymin = range_min, ymax = range_max)) +
  ggrepel::geom_text_repel(
    data = . %>% filter(decade == "decade_00s"),
    mapping = aes(y = mean, label = region)
    )

reprex package(v0.2.0)创建于2018-06-15。

相关问题