关于ggplot2:R geom_path行有时会“关闭”。 如何保持它们“开放”?

R geom_path lines “closing”, sometimes. How to keep them “open”?

我正在用ggplot的geom_path()绘制一系列财务预测。

1
ggplot(df,aes(year,pot,color=iRate)) + geom_path() +  theme(legend.position="none") + ylim(0,300000)

这就是我所拥有的.. [对不起,这是一个链接]

problem graph

.. 40年中,有两条道路碰到了右手边,但随后又回到了起点。 一行没有。 这不是轴显示限制的问题,也不是数据框中的流氓线的问题-如果我删除所有小于5的年份,则会发生相同的情况。
这可能是使绘图设备负担过重的一个正义问题,但这是可重复的。

有一些问题询问如何"关闭" geom_path,但无法回答此问题。 如何确保路径保持"开放"状态?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
inflation <- seq(1, 1.1, 0.02)
potGrowth <- seq(1.02, 1.1, 0.02)
div <- 10000
initcapital <- 100000
output <- numeric()
lifespan <- 40
delay <- 10
for(j in 1:length(inflation)){
    str <- rep(0,lifespan)
    for(i in delay:lifespan){ str[i] <- floor((inflation[j]^i)*div) }
    for(k in 1:length(potGrowth)){
        cap <- initcapital
        for(i in 1:lifespan){  
        cap <- cap-str[i]; cap <- cap*potGrowth[k]
        output <-  append(output, floor(cap))
        }
    }
}
iLen <- length(inflation); gLen <- length(potGrowth)
simulations <- iLen*gLen    
df <- data.frame(pot=output, projection=rep(1:simulations,each=lifespan), iRate=rep(inflation,each=lifespan*gLen), gRate=rep(rep(potGrowth,each=lifespan),times=iLen), year=rep(1:lifespan,times=simulations))

这是通过插入group = projection解决的

ggplot(df,aes(year,pot,color = iRate,group = projection))+ geom_path()...

非问题图


感谢@aosmith在您的评论中提到参数group。 这是一个可再现的示例,描述了空气质量数据集的路径关闭问题。 假设您要绘制每个月各天的温度图表。 将所有月份都放在同一图上(本着这些年度图的精神:arcticseaicenews)。

单独使用geom_path()会导致上个月最后一天和下个月第一天之间令人讨厌的"关闭"行。

1
2
3
library(ggplot2)
ggplot(airquality, aes(x = Day, y = Temp)) +
    geom_path()

No group

geom_path()与参数group=Month一起使用可防止出现以下几行:

1
2
ggplot(airquality, aes(x = Day, y = Temp, group=Month)) +
    geom_path()

group

当然,您还可以根据需要使用facet_wrap在不同的方面显示月份:

1
2
3
ggplot(airquality, aes(x = Day, y = Temp)) +
    geom_path() +
    facet_wrap(~Month)