R geom_path行"关闭",有时。如何保持他们"开放"?

时间:2016-07-21 13:19:52

标签: r ggplot2

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

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

这就是我的...... [对不起它是一个链接]

problem graph

..其中两条路径在40年右手边缘击中,但随后又回到了开始状态。一条线不是。这不是轴显示限制的问题,也不是数据框中的流氓线的问题 - 如果我删除所有年份< 5同样的事情发生了。 这可能是绘图设备负担过重的一个问题,但它是可重复的。

有些问题询问如何关闭'一个没有回答这个问题的geom_path。如何确保路径保持打开状态?

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(年,锅,颜色= iRate,组=投影))+ geom_path()......

non-problem graph

1 个答案:

答案 0 :(得分:1)

感谢@aosmith在评论中提到参数group。这是一个可重现的示例,描述了空气质量数据集的路径关闭问题。假设您想绘制每个月的温度图表。将所有月份保持在相同的情节中(根据这些年度情节的精神:arcticseaicenews)。

单独使用geom_path()导致在上个月的最后一天和下个月的第一天之间出现令人讨厌的“关闭”线。

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

No group

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

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

group

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

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