【问题标题】:How can I add a point in xy line in R?如何在 R 的 xy 线上添加一个点?
【发布时间】:2015-12-01 16:20:07
【问题描述】:

我有一个有 2 条线的折线图。但我想显示两条线重叠的点。如果我用线条显示点会更好。

Q<-8
xdata <- seq(1,Q*2,1)
HCdata <- matrix(1,1)
OCdata <- matrix(1,1)

for (i in xdata) {

  OC<-(100/i)*100
  HC<-(i/2)*20*20
  HCdata[i]<- HC
  OCdata[i]<- OC

}

holdingcost <- data.frame(holdingcost=HCdata)
orderingcost <- data.frame(orderingcost=OCdata)
xx<-cbind(holdingcost,orderingcost)
y <- ggplot(xx, aes(xdata)) 
y1 <- y +  geom_line(size=1,aes(y=holdingcost, colour = "holdingcost")) 
y1 <- y1 + geom_line(size=1,aes(y=orderingcost, colour = "orderingcost")) 

【问题讨论】:

  • 为了将来参考,您可以创建没有循环的数据框,如下所示:xx = data.frame(xdata, holdingcost = xdata/2 * 20 * 20, orderingcost = 100/xdata * 100)

标签: r ggplot2 linechart


【解决方案1】:

找到最接近相等的 x 值:

eq <- xx[which.min(abs(xx$holdingcost - xx$orderingcost)), ]

加点:

y1 + geom_point(data = eq, aes(y = holdingcost), size = 2)

【讨论】:

  • 不幸的是,它不适用于更高的值。 Q
  • 问题不在于高值,而在于您只有 4 个值,并且指向最接近的值。你必须做插值来解决这个问题,或者改变你的for循环(你根本不需要,正如@eipi10所提到的)。
猜你喜欢
  • 2010-12-01
  • 2023-03-27
  • 2020-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
相关资源
最近更新 更多