Lattice xyplot does not show all levels of factor on Y axis: incomplete plot

问题

我使用Lattice中的xyplot()绘制由具有 3 列的数据框定义的箭头:位置(数字)、从(字符)到(字符)。 问题:有时,箭头会超出情节的范围。 换句话说,绘图窗口不足以可视化所有数据。

我尝试明确添加因子水平,但无济于事。 似乎如果更极端的水平(例如“D”)不存在于因子“df$from”中,则这些水平不计入绘制绘图窗口。 我查看了ylim但这仅限于数值。

我环顾四周,发现了很多关于重新缩放、重新排序轴的内容,但没有任何东西可以帮助我解决手头的问题。 这个问题与@skan 的一个问题有关:如何在 Lattice 中绘制线段或箭头。

我的数据:

l <- c("A", "B", "C", "D")
df <- data.frame(posi = c(1, 2, 3, 4, 5), 
                 from = factor(c("A", "B", "C", "D", "A"), levels = l, ordered = TRUE),
                 to = factor(c("C", "D", "D", "C", "A"), levels = l, ordered = TRUE)
)

这按预期绘制:

xyplot(from ~ posi , type="p", col="black",  data=df, pch=16, xlim = c(0,7), 
       panel = function(...){
         panel.dotplot(x = df$posi, y = df$from, col ="green", cex=1.6)
         panel.dotplot(x = (df$posi+1), y = df$to, col="black", cex=1.)
         panel.arrows(x0 = df$posi, y0 = df$from, x1 = df$posi+1, y1 = df$to, lwd=2, col="blue" )
       }
)

当我只使用具有“旧”因子水平的相同数据框的前 3 行时,该图没有考虑到稍后将需要“D”水平。

## only first 3 rows, without element "D" in the factor df$from
df <- df[1:3, ] 

导致这个情节:

我希望能够设置 Y 轴的限制,并希望得到任何帮助或提示。

回答1

通过在 xyplot 的调用中指定“drop.unused.levels = FALSE”可以避免该问题。

library(lattice)

l <- c("A", "B", "C", "D")
df <- data.frame(posi = c(1, 2, 3, 4, 5), 
             from = factor(c("A", "B", "C", "D", "A"), levels = l, 
                           ordered = TRUE),
             to = factor(c("C", "D", "D", "C", "A"), levels = l, 
                         ordered = TRUE))


xyplot(from ~ posi , type="p", col="black",  data=df, pch=16, xlim = c(0,7), 
   panel = function(...){
     panel.dotplot(x = df$posi, y = df$from, col ="green", cex=1.6)
     panel.dotplot(x = (df$posi+1), y = df$to, col="black", cex=1.)
     panel.arrows(x0 = df$posi, y0 = df$from, x1 = df$posi+1, y1 = df$to, 
                  lwd=2, col="blue" )
   })

df2 <- df[1:3,]
xyplot(from ~ posi , type="p", col="black",  data=df2, pch=16, xlim = c(0,7), 
   drop.unused.levels = FALSE,
   panel = function(...){
     panel.dotplot(x = df2$posi, y = df2$from, col ="green", cex=1.6)
     panel.dotplot(x = (df2$posi+1), y = df2$to, col="black", cex=1.)
     panel.arrows(x0 = df2$posi, y0 = df2$from, x1 = df2$posi+1, 
                  y1 = df2$to, lwd=2, col="blue" )
   })

标签

更多相关内容:请点击查看