有一些变通方法,但看起来您可能对每个州都有这些值,并通过方面来组织它们。在这种情况下,让我们尽量使用“tidy”。在这个构造的假数据中,为简单起见,我更改了您的变量名称,但概念是相同的。
library(dplyr)
library(purrr)
library(ggplot2)
temp.grp <- expand.grid(state = sample(state.abb, 8), year = 2008:2015) %>%
# sample 8 states and make a dataframe for the 8 years
group_by(state) %>%
mutate(sval = cumsum(rnorm(8, sd = 2))+11) %>%
# for each state, generate some fake data
ungroup %>% group_by(year) %>%
mutate(nval = mean(sval))
# create a "national average" for these 8 states
head(temp.grp)
Source: local data frame [6 x 4]
Groups: year [1]
state year sval nval
<fctr> <int> <dbl> <dbl>
1 WV 2008 15.657631 10.97738
2 RI 2008 10.478560 10.97738
3 WI 2008 14.214157 10.97738
4 MT 2008 12.517970 10.97738
5 MA 2008 9.376710 10.97738
6 WY 2008 9.578877 10.97738
这会画出两条丝带,一条位于全国平均水平线之间,以较小者为准,即全国平均水平或州值。这意味着当全国平均水平较低时,它本质上是一条高度为 0 的丝带。当全国平均水平较高时,丝带位于全国平均水平和较低的州值之间。
另一个功能区与此相反,当状态值较小时为 0 高度,当状态值较高时在两个值之间拉伸。
ggplot(temp.grp, aes(year, nval)) + facet_wrap(~state) +
geom_ribbon(aes(ymin = nval, ymax = pmin(sval, nval), fill = "State lower")) +
geom_ribbon(aes(ymin = sval, ymax = pmin(sval, nval), fill = "State higher")) +
geom_line(aes(linetype = "Nat'l Avg")) +
geom_line(aes(year, sval, linetype = "State")) +
scale_fill_brewer(palette = "Set1", direction = -1)
这主要是可行的,但是你可以看到交叉点发生的地方有点奇怪,因为它们并没有在年份 x 值处精确交叉:
要解决此问题,我们需要沿每个线段进行插值,直到这些间隙变得肉眼无法区分。我们将为此使用purrr::map_df。我们首先将split 数据放入一个数据帧列表中,每个状态一个。然后,我们沿该列表map 创建一个数据框,其中包含 1) 插值年份和州值,2) 插值年份和全国平均值,以及 3) 每个州的标签。
temp.grp.interp <- temp.grp %>%
split(.$state) %>%
map_df(~data.frame(state = approx(.x$year, .x$sval, n = 80),
nat = approx(.x$year, .x$nval, n = 80),
state = .x$state[1]))
head(temp.grp.interp)
state.x state.y nat.x nat.y state
1 2008.000 15.65763 2008.000 10.97738 WV
2 2008.089 15.90416 2008.089 11.03219 WV
3 2008.177 16.15069 2008.177 11.08700 WV
4 2008.266 16.39722 2008.266 11.14182 WV
5 2008.354 16.64375 2008.354 11.19663 WV
6 2008.443 16.89028 2008.443 11.25144 WV
approx 函数默认返回一个名为 x 和 y 的列表,但我们将其强制转换为数据框并使用 state = 和 nat = 参数重新标记它。请注意,插值的年份在每一行中都是相同的值,因此我们可以在这一点上丢弃其中一列。我们也可以重命名列,但我将不理会它。
现在我们可以修改上面的代码来处理这个新创建的插值数据帧。
ggplot(temp.grp.interp, aes(nat.x, nat.y)) + facet_wrap(~state) +
geom_ribbon(aes(ymin = nat.y, ymax = pmin(state.y, nat.y), fill = "State lower")) +
geom_ribbon(aes(ymin = state.y, ymax = pmin(state.y, nat.y), fill = "State higher")) +
geom_line(aes(linetype = "Nat'l Avg")) +
geom_line(aes(nat.x, state.y, linetype = "State")) +
scale_fill_brewer(palette = "Set1", direction = -1)
现在十字路口干净多了。此解决方案的分辨率由对approx(...) 的两次调用的n = 参数控制。