How to plot segments or arrows with Lattice in R? (from a Wide format dataset)

前端 未结 1 1470
别那么骄傲
别那么骄傲 2021-01-16 06:01

I would like to create a plot with segements or arrows.

Let\'s say I have this toy example

temp <- data.frame(posi=c(1,2,3,3,2,1,5), from=c(\"A\",         


        
相关标签:
1条回答
  • You could use the following code:

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

    yielding the following graph:

    Please let me know whether this is what you want.

    UPDATE

    I posted a question concerning the problem that @skan identified and described in the comments: when a "extreme" level (like "D") is not present in temp$from then the "D" will not part of the graph, even when "D" will be needed later for temp$to. The question with answer from @Konn may be found here.

    As I understand it now, we need a factor that is ordered, and we need an addition to the code specifying drop.unused.levels = FALSE in the call to xyplot. In the example we show the full set with "extremes" in "from" and as subset where the extreme "D" is absent: The full code is:

    l <- c("A", "B", "C", "D")
    temp <- data.frame(posi = c(1, 2, 3, 3, 2), 
                       from= factor(c("A", "B", "C", "D", "D"), levels = l, ordered = TRUE),
                       to = factor(c("C", "D", "D", "C", "A"), levels = l, ordered = TRUE)
                       ) 
    
    
    xyplot(from ~ posi , type="p", col="black",  data=temp, pch=16, xlim = c(0,7), 
           drop.unused.levels = FALSE,  ## the added code
           panel = function(...){
             panel.dotplot(x = temp$posi, y = temp$from, col ="green", cex=1.6)
             panel.dotplot(x = (temp$posi+1), y = temp$to, col="black", cex=1.)
             panel.arrows(x0 = temp$posi, y0 = temp$from, x1 = temp$posi+1, y1 = temp$to, lwd=2, col="blue" )
           })
    
    temp <- temp[1:3, ]
    xyplot(from ~ posi , type="p", col="black",  data=temp, pch=16, xlim = c(0,7), 
           drop.unused.levels = FALSE,  ## the added code
           panel = function(...){
             panel.dotplot(x = temp$posi, y = temp$from, col ="green", cex=1.6)
             panel.dotplot(x = (temp$posi+1), y = temp$to, col="black", cex=1.)
             panel.arrows(x0 = temp$posi, y0 = temp$from, x1 = temp$posi+1, y1 = temp$to, lwd=2, col="blue" )
           })
    

    yielding the following pics:

    I think we have solved this question.

    0 讨论(0)
提交回复
热议问题