R plotly 3d bar plot

时间:2016-10-24 13:56:23

标签: r shiny plotly

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

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

1 个答案:

答案 0 :(得分: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