Home > Back-end >  Combing Treemaps with Plotly
Combing Treemaps with Plotly

Time:05-12

I working with Plotly and I want to combine two Treemap at the same time. I tried to do this with a subplot but is not working. Below you can see code

library(plotly)
library(dplyr)

dt=data.frame(
          types= rep("stories",10),
          kind= c('kind_1','kind_2','kind_3','kind_1','kind_2','kind_3','kind_1','kind_2','kind_3','kind_1'),
          values=seq(1:10))
        


Treemap1<-plot_ly(data = dt,
                 type= "treemap",
                 values= ~values,
                 labels= ~kind,
                 parents=  ~types,
                 domain= list(column=0),
                 name = " ",
                 textinfo="label value percent parent")%>%
    layout(title="Treemap1")

Treemap1

Treemap2<-plot_ly(data = dt,
                  type= "treemap",
                  values= ~values,
                  labels= ~kind,
                  parents=  ~types,
                  domain= list(column=0),
                  name = " ",
                  textinfo="label value percent parent")%>%
  layout(title="Treemap2")


subplot(Treemap1,Treemap2)

Can anybody help me with how to solve this problem and to have this two Treemap on same plot ?

CodePudding user response:

The best that I could come up with was adding a manual title an uninherited trace. This achieves your goal. I don't know what subplot is being difficult. You might have to adjust the white space between titles. I tried to use HTML to control it, but it rendered the literal HTML on the plot.

I used margin because it added an uneven right-left margin and Plotly always smashes the title at the top. (No wasted space and all that.)

(Treemap1 <- plot_ly(data = dt,
                     type= "treemap",
                     values= ~values,
                     labels= ~kind,
                     parents=  ~types,
                     domain= list(column=0),
                     name = " ",
                     textinfo="label value percent parent"))

(Treemap2 <- Treemap1 %>% 
  add_trace(inherit = F,
            data = dt,
            type= "treemap",
            values= ~values,
            labels= ~kind,
            parents=  ~types,
            domain= list(column=1),
            name = " ",
            textinfo="label value percent parent") %>% 
    layout(grid = list(columns = 2, rows = 1),
           title = paste0("<b style='display:inline-block;float: left;'>",
                          "Treemap 1",
                          "                                        ",
                          "Treemap 2"),
           margin = list(t = 50, l = 30, r = 30, b = 30)))

enter image description here

  • Related