我正在使用 ggplot 的 geom_path() 绘制一系列财务预测。
ggplot(df,aes(year,pot,color=iRate)) + geom_path() + theme(legend.position="none") + ylim(0,300000)
Run Code Online (Sandbox Code Playgroud)
这就是我所拥有的..[抱歉,这是一个链接]
..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))
Run Code Online (Sandbox Code Playgroud)
这里通过插入 group=projection 来解决
ggplot(df,aes(年份,pot,颜色=iRate,组=投影)) + geom_path() ...
group
感谢@aosmith在评论中提到这个论点。这是一个可重现的示例,描述了空气质量数据集的路径关闭问题。假设您想要绘制每个月各天的温度图表。将所有月份保持在同一情节上(本着这些年度情节的精神:arcticseaicenews)。
单独使用geom_path()
会导致上个月最后一天和下个月第一天之间出现烦人的“结束”线。
library(ggplot2)
ggplot(airquality, aes(x = Day, y = Temp)) +
geom_path()
Run Code Online (Sandbox Code Playgroud)
geom_path()
与参数一起使用group=Month
可防止出现这些行:
ggplot(airquality, aes(x = Day, y = Temp, group=Month)) +
geom_path()
Run Code Online (Sandbox Code Playgroud)
当然,您也可以facet_wrap
根据您的需要在不同方面显示月份:
ggplot(airquality, aes(x = Day, y = Temp)) +
geom_path() +
facet_wrap(~Month)
Run Code Online (Sandbox Code Playgroud)