【问题标题】:R geom_path lines "closing", sometimes. How to keep them "open"?R geom_path 有时会“关闭”行。如何保持它们“开放”?
【发布时间】:2016-11-25 02:46:49
【问题描述】:

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

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

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

..其中两条路径在 40 年到达右侧边缘,但随后又回到了起点。一条线没有。这不是轴显示限制的问题,也不是数据框中的流氓行的问题 - 如果我删除所有

有一些问题询问如何“关闭”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(year,pot,color=iRate,group=projection)) + geom_path() ...

non-problem graph

【问题讨论】:

  • 您可以使用 dput() 发布您的数据样本吗?
  • 尝试更改 ylim,我可以在图中看到它在 ylim(0,300000) 处停止。增加它或将其留空。
  • 在您发布的数据集中,iRate 的单个值每年都会遍历两次。所以geom_path 绘制了第一个年份序列,然后必须回到开头为相同的iRate 绘制第二个年份序列。看起来这与projection 有关,您可能希望以某种方式将其合并到图表中(也许group by projection?)。
  • 我用您的代码绘制了示例数据集,并且单个iRate 有多个年份序列,这导致线条回到开头(所以geom_path 正在绘制数据正确)。如果我添加了group = projection,它就不会发生,尽管这对于您想要显示的任何内容都可能没有意义。
  • 这正是我想要的。我不熟悉 group=。非常感谢

标签: r ggplot2


【解决方案1】:

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

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

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

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

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

当然,您也可以使用 facet_wrap 在不同方面显示月份,具体取决于您的需求:

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

【讨论】:

  • 你救了我的命,分组才是解决办法!!
猜你喜欢
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多