如何在R中的现有晶格图上添加新点

问题描述:

我使用了 lattice 软件包绘制了一条线图.

I used the lattice package to draw a line plot.

library(lattice)  
xyplot(price~month,groups=perc,data=Edf,type='l',
       main="Percentile chart of OpRes Charge Rates Forcast", 
       ylab="OpRes Charge Rate ($/MWh)", xlab="Months",ylim=c(0,40),auto.key=TRUE)

然后,我想在现有绘图中添加一些点.

Then I wanted to add some dots to the existing plot.

points(rep(1,length(OpResWestJan)),OpResWestJan) 

OpResWestJan是矢量,但是点在现有绘图中从未出现,并且没有警告.

OpResWestJan is a vector, but the dots never appeared in the existing plot, and there were no warnings.

为完整起见,这是一个可复制的示例.只需将创建的xyplot存储在变量中,然后将update与自定义panel函数一起使用即可添加其他点.

For the sake of completeness, here is a reproducible example. Simply store the created xyplot in a variable and then use update along with a custom panel function to add additional points.

library(lattice)

## create scatterplot
p <- xyplot(1:10 ~ 1:10)

## insert additional points
update(p, panel = function(...) {
  panel.xyplot(...)
  panel.xyplot(1:10, 10:1, pch = 4, col = "orange")
})

或者,您也可以创建第二个xyplot并使用 latticeExtra 中的as.layer将其添加到初始绘图中.

Alternatively, you can also create a second xyplot and use as.layer from latticeExtra to add it to your initial plot.

library(latticeExtra)

## create second scatterplot and add it to first plot
p2 <- xyplot(10:1 ~ 1:10, pch = 4, col = "orange")
p + as.layer(p2)

或者按照@Pascal的建议,将layerpanel.points一起使用以实现您的目标.

Or, as suggested by @Pascal, use layer alongside with panel.points to achieve your goal.

p + layer(panel.points(1:10, 10:1, pch = 4, col = "orange"))