【问题标题】:Lattice xyplot does not show all levels of factor on Y axis: incomplete plot格子 xyplot 未在 Y 轴上显示所有级别的因子:不完整的图
【发布时间】:2017-06-23 09:37:01
【问题描述】:

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

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

我在 SO 上环顾四周,发现了很多关于重新缩放、重新排序轴的内容,但没有任何东西可以帮助我解决手头的问题。这个问题与@skan 的一个问题有关:How to plot segments or arrows in 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 轴的限制,如果有任何帮助或提示,我将不胜感激。

【问题讨论】:

    标签: r plot lattice


    【解决方案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" )
       })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      相关资源
      最近更新 更多