R plotly 3d条形图

R plotly 3d bar plot

对于嵌入在 R shiny 输出中的交互式 3D 图,R 包 plotly 现在提供了一些不错的选择,特别是最近对替代 shiny-rgl 包的维护似乎正在消失。

但是,是否可以使用 plotly 创建 3d 条形图?

创建 3d 条形图外观的一个技巧是绘制误差线。

正如在下面的代码中所评论的那样,在通过 add_trace 提供它们之前,需要条形的维度值减半,在那里它们被调整到可见性以下的任何值(或使它们透明)。减半值的对称误差条然后简单地导致条。下面的例子中添加了两组数据df1df2

library(shiny)
library(plotly)

ui <- fluidPage(
    plotlyOutput("plotlii", width = "100%", height = "700px")
)

server <- function(input, output) {
    output$plotlii <- renderPlotly({
        # the data:     
        obs1 <- matrix(ncol=3,
            c(1,2,3,1,2,2,6,6,4)
        )
        df1 <- setNames(data.frame(obs1), c("a", "b", "c"))
        df1$c<-(.5*df1$c) # half values to make them the centre point of the bars
        obs2 <- matrix(ncol=3,
            c(14,16,10,11,12,12,23,23,22)
        )
        df2 <- setNames(data.frame(obs2), c("a", "b", "c"))
        df2$c<-(.5*df2$c) # half values to make them the centre point of the bars
        # the plot:
        p <- plot_ly(type="scatter3d",mode="markers",showlegend=FALSE)%>%
        add_trace(p,
            x = ~a, y = ~b, z = ~c,
            data = df1,
            color=I("red"),
            size = I(1),
            name = "Group a",
            error_z=list(
                color="red",
                thickness=0,
                symmetric = TRUE, 
                type = "data" ,
                array = df1$c
            )
        )%>%
        add_trace(p,
            x = ~a, y = ~b, z = ~c,
            data = df2,
            color=I("gray"),
            size = I(1),
            name = "Group a",
            error_z=list(
                color="gray",
                symmetric = TRUE, 
                type = "data" ,
                array = df2$c
            )
        )   
    })
}

shinyApp(ui, server)