r xyplot以“数据点为中心”的“步骤”

时间:2013-02-08 19:39:28

标签: r lattice

xyplot()的类型参数可以用“s”表示“步骤”。来自help(plot)

  

两个步骤类型的x-y偏好不同:来自        (x1,y1)至(x2,y2),其中x1

即。如果您使用type="s",则步骤的水平部分的左端连接到数据点,而type="S"的右端连接到数据点。

library(lattice)
set.seed(12345)
num.points <- 10
my.df <- data.frame(x=sort(sample(1:100, num.points)),
                    y=sample(1:40, num.points, replace=TRUE))

xyplot(y~x, data=my.df, type=c("p","s"), col="blue", main='type="s"')
xyplot(y~x, data=my.df, type=c("p","S"), col="red", main='type="S"')

type='s'

type='S'

如何实现“阶梯”图,其中垂直运动发生在数据点之间,即x1 + (x2-x1)/2处,以便步骤的水平部分以数据点为中心?

编辑包含一些示例代码。迟到总比我想的要好。

2 个答案:

答案 0 :(得分:2)

这是一个基础图形解决方案,因为我不是lattice的专家。

基本上你可以使用segments首先绘制水平,然后绘制垂直步骤,将移动的坐标作为矢量绘制。

以下是一个例子:

set.seed(12345)

# Generate some data
num.points <- 10
x <- sort(sample(1:100, num.points))
y <- sample(1:40, num.points, replace=T)


# Plot the data with style = "s" and "S"
par(mfrow=c(1,3))

plot(x, y, "s", col="red", lwd=2, las=1, 
     main="Style: 's'", xlim=c(0, 100))
points(x, y, pch=19, col="red", cex=0.8)

plot(x, y, "S", col="blue", lwd=2, las=1, 
     main="Style: 'S'", xlim=c(0, 100))
points(x, y, pch=19, col="blue", cex=0.8)

# Now plot our points
plot(x, y, pch=19, col="orange", cex=0.8, las=1, 
     main="Centered steps", xlim=c(0, 100))

# Calculate the starting and ending points of the
# horizontal segments, by shifting the x coordinates
# by half the difference with the next point
# Note we leave the first and last point as starting and
# ending points
x.start <- x - (c(0, diff(x)/2))
x.end <- x + (c(diff(x)/2, 0))

# Now draw the horizontal segments
segments(x.start, y, x.end, y, col="orange", lwd=2)
# and the vertical ones (no need to draw the last one)
segments(x.end[-length(x.end)], y[1:(length(y)-1)], 
         x.end[-length(x.end)], y[-1], col="orange", lwd=2)

结果如下: Step plots

答案 1 :(得分:2)

我使用优秀的@nico答案来给它的格子版本。即使我对@Dwin也没问题,因为这个问题没有提供可重复的例子,但定制格子面板有时很有挑战性。 我们的想法是使用panel.segments,它相当于基础图形的segments

library(lattice)
xyplot(y~x,
       panel =function(...){
         ll <- list(...)
         x <- ll$x
         y <- ll$y
         x.start <- x - (c(0, diff(x)/2))
         x.end   <- x + (c(diff(x)/2, 0))
         panel.segments(x.start, y, x.end, y, col="orange", lwd=2)
         panel.segments(x.end[-length(x.end)], y[1:(length(y)-1)], 
                        x.end[-length(x.end)], y[-1], col="orange", lwd=2)
         ## this is optional just to compare with type s
         panel.xyplot(...,type='s')
         ## and type S
         panel.xyplot(...,type='S')
       })

enter image description here