R plotly 3d 条形图

3
对于嵌入R shiny输出的交互式3D图,R包plotly现在提供了一些不错的选项,特别是考虑到替代方案shiny-rgl的维护最近似乎已经消失了。但是,是否可以使用plotly创建3D条形图呢?

1
回答自己的问题是可以的,但我不太明白你在解决什么问题。通过添加一些关于“技巧”是什么以及它如何工作的解释,以及结果的图像,可以改进答案。 - Axeman
修改后以使观点更清晰。在R中运行以下答案代码以显示交互式3D图。 - martin
1个回答

2

创建 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)

enter image description here


@Martin,是的,它确实有影响,但影响程度比获得采纳答案要小! - massisenergy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接