【问题标题】:Adding independent title to each subplot in plotly R在 plotly R 中为每个子图添加独立标题
【发布时间】:2023-01-20 02:27:43
【问题描述】:

我正在尝试在 R 中生成一个与 website 中描述的类似的情节图,并使用 Python 生成。这是一个水平条形图,它是通过将多个子图相互堆叠而创建的。

情节看起来像:

我快接近了,但我无法完全重现它。剧情的方式大致是这样的:

  • 为每个需要的类别制作一个条形图,并带有适当的标题和文本
  • 使用make_subplot 函数堆叠所有绘图
  • 删除不必要的标签并正确格式化文本。

到目前为止,我面临的最大问题是我无法重复主情节中每个子情节的标题。

这是我的代码。请注意,每个图都有不同的标题:

library(plotly)

# preparing bogus data
d <- data.frame(question = paste0("Question ", 1:10),
                value = seq(20, 1, -2))

# setting up a list to store the plots
ls_p <- NULL

# Create one plot (subplot) for each categories in my data
for(i in 1:nrow(d)){
  ls_p[[i]] <- plot_ly(d[i,], x=~value, y=~question) |>
    add_bars(orientation='h') |> #
    add_text(x=~value, y=~question, text=~value) |>
    layout(title = list(text=d$question[i],
                        xanchor = "left",
                        align = "left"),
           showlegend=F,
           grid=list(showgrid=F),
           xaxis=list(range=c(0,max(d$value)),
                      showticklabels =F),
           yaxis=list(showticklabels = F)
           )
}

# regroup all the subplots together
subplot(ls_p, nrows= nrow(d), shareX = T, which_layout = 1, titleX = F, titleY = F)

此代码产生:

这是错误的多种方式:

  • 只写了第一个情节的标题,所有后续情节都没有标题
  • 标题没有左对齐
  • 文本(值)居中到条的末端,没有保留在内部右侧部分
  • 第一个和最后一个条比其他条粗。

有一种方法可以在 plotly-R 中生成这种图形,还是我们仅限于 plotly-python?

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    您可以在 layout 中使用 annotationstext 而不是标题。这是一个可重现的例子:

    library(plotly)
    
    # preparing bogus data
    d <- data.frame(question = paste0("Question ", 1:10),
                    value = seq(20, 1, -2))
    
    # setting up a list to store the plots
    ls_p <- NULL
    
    # Create one plot (subplot) for each categories in my data
    for(i in 1:nrow(d)){
      ls_p[[i]] <- plot_ly(d[i,], x=~value, y=~question) |>
        add_bars(orientation='h') |> #
        add_text(x=~value, y=~question, text=~value) |>
        layout(annotations = list(text = d$question[i],
                                  showarrow = FALSE),
               showlegend=F,
               grid=list(showgrid=F),
               xaxis=list(range=c(0,max(d$value)),
                          showticklabels =F),
               yaxis=list(showticklabels = F)
        )
    }
    
    # regroup all the subplots together
    subplot(ls_p, nrows= nrow(d), shareX = T, which_layout = 1, titleX = F, titleY = F) 
    

    创建于 2023-01-19 reprex v2.0.2

    【讨论】:

      猜你喜欢
      • 2019-01-06
      • 1970-01-01
      • 2019-05-28
      • 2020-05-10
      • 2021-03-13
      • 2018-01-19
      • 1970-01-01
      • 2018-09-14
      • 2017-05-10
      相关资源
      最近更新 更多