首页 > 解决方案 > 在情节中添加线条

问题描述

我创建了一个 3x3x3 点的立方体,范围从 -1 到 1。我想绘制水平线和垂直线来连接点,以使其更易于可视化。我该怎么做?下面的代码是我要做的:

library(plotly) 
library(shiny) 
ui <- fluidPage( 
plotlyOutput("plot"), 
verbatimTextOutput("hover"), 
verbatimTextOutput("click") ) 

server <- function(input, output, session) { 

output$plot <- renderPlotly({ 
plot_ly(x = c(-1, -1, -1, -1, -1, -1, -1, -1, -1,
               0,  0,  0,  0,  0,  0,  0,  0,  0,
               1,  1,  1,  1,  1,  1,  1,  1,  1),

        y = c(-1, -1, -1,  0,  0,  0,  1,  1,  1,
              -1, -1, -1,  0,  0,  0,  1,  1,  1,
              -1, -1, -1,  0,  0,  0,  1,  1,  1), 

        z = c(-1,  0,  1,  -1, 0,  1, -1,  0,  1,
              -1,  0,  1,  -1, 0,  1, -1,  0,  1,
              -1,  0,  1,  -1, 0,  1, -1,  0,  1), type = "scatter3d")  
}) 

 output$hover <- renderPrint({ 
d <- event_data("plotly_hover") 
if (is.null(d)) "Hover events appear here (unhover to clear)" else d 
}) 

  output$click <- renderPrint({ 
d <- event_data("plotly_click") 
if (is.null(d)) "Click events appear here (double-click to clear)" else d 
}) 

} 

shinyApp(ui, server)

谢谢!

标签: plotly

解决方案


也许这可以向您展示一种方式:

library(plotly) 
library(shiny) 
ui <- fluidPage( 
  plotlyOutput("plot"), 
  verbatimTextOutput("hover"), 
  verbatimTextOutput("click") ) 

df <- data.frame(
  x = c(-1, -1, -1, -1, -1, -1, -1, -1, -1,
        0,  0,  0,  0,  0,  0,  0,  0,  0,
        1,  1,  1,  1,  1,  1,  1,  1,  1),
  y = c(-1, -1, -1,  0,  0,  0,  1,  1,  1,
        -1, -1, -1,  0,  0,  0,  1,  1,  1,
        -1, -1, -1,  0,  0,  0,  1,  1,  1),
  z = c(-1,  0,  1,  -1, 0,  1, -1,  0,  1,
        -1,  0,  1,  -1, 0,  1, -1,  0,  1,
        -1,  0,  1,  -1, 0,  1, -1,  0,  1)
)
li <- data.frame(
  x = c( 1,  0, -1, -1, -1),
  y = c( 1,  1,  1,  1,  1),
  z = c(-1, -1, -1,  0,  1)
)

server <- function(input, output, session) { 

  output$plot <- renderPlotly({ 

    plot_ly() %>% 
      add_markers(data = df, x=~x, y=~y, z=~z, mode = 'markers', type = 'scatter3d') %>% 
      add_markers(data = li, x = ~x, y=~y, z=~z, type = 'scatter3d', mode = 'lines',
                  line = list(width = 6, color = "red"), inherit = F)
  }) 

  output$hover <- renderPrint({ 
    d <- event_data("plotly_hover") 
    if (is.null(d)) "Hover events appear here (unhover to clear)" else d 
  }) 

  output$click <- renderPrint({ 
    d <- event_data("plotly_click") 
    if (is.null(d)) "Click events appear here (double-click to clear)" else d 
  }) 

} 

shinyApp(ui, server)

推荐阅读