代码之家  ›  专栏  ›  技术社区  ›  dan

在plotly::子地块中显示所有地块标题

  •  6
  • dan  · 技术社区  · 7 年前

    我有两个密度图,由 R plotly :

    set.seed(1)
    
    dens.1 <- density(runif(1000,0,100))
    dens.2 <- density(runif(1000,100,10000))
    
    df.1 <- data.frame(x=dens.1$x,y=dens.1$y)
    df.2 <- data.frame(x=dens.2$x,y=dens.2$y)
    
    library(plotly)
    
    pl.1 <- plot_ly(x=~df.1$x,y=~df.1$y,type='scatter',mode='lines',line=list(color="#A9A9A9")) %>%
      layout(xaxis=list(title="Count",zeroline=F),yaxis=list(title="Density",zeroline=F)) %>%
      layout(title="Data1")
    
    pl.2 <- plot_ly(x=~df.2$x,y=~df.2$y,type='scatter',mode='lines',line=list(color="#A9A9A9")) %>%
      layout(xaxis=list(title="Count",zeroline=F),yaxis=list(title="Density",zeroline=F)) %>%
      layout(title="Data2")
    

    现在,我想把它们画在一起。所以我用 绘声绘色地 subplot :

    subplot(list(pl.1,pl.2),nrows=1,shareX=F,shareY=F,titleX=T,titleY=T) %>% layout(showlegend=F)
    

    但这只保留了 pl.2 : enter image description here

    我如何在那个情节中同时获得两个标题?

    1 回复  |  直到 7 年前
        1
  •  6
  •   MLavoie    7 年前

    为了得到你想要的( https://rpubs.com/bcd/subplot-titles )您可以使用:

    a <- list(
      text = "Data 1",
      font = f,
      xref = "paper",
      yref = "paper",
      yanchor = "bottom",
      xanchor = "center",
      align = "center",
      x = 0.5,
      y = 1,
      showarrow = FALSE
    )
    
    b <- list(
      text = "Data 2",
      font = f,
      xref = "paper",
      yref = "paper",
      yanchor = "bottom",
      xanchor = "center",
      align = "center",
      x = 0.5,
      y = 1,
      showarrow = FALSE
    )
    
    pl.1 <- plot_ly(x=~df.1$x,y=~df.1$y,type='scatter',mode='lines',line=list(color="#A9A9A9")) %>%
      layout(xaxis=list(title="Count",zeroline=F),yaxis=list(title="Density",zeroline=F)) %>%
      layout(annotations = a)
    
    pl.2 <- plot_ly(x=~df.2$x,y=~df.2$y,type='scatter',mode='lines',line=list(color="#A9A9A9")) %>%
      layout(xaxis=list(title="Count",zeroline=F),yaxis=list(title="Density",zeroline=F)) %>%
      layout(annotations = b)
    
    subplot(list(pl.1,pl.2),nrows=1,shareX=F,shareY=F,titleX=T,titleY=T) %>% layout(showlegend=F)