[英]Adding independent title to each subplot in plotly R
我正在嘗試在 R 中生成與本網站中描述的類似的 plotly plot,並使用 Python 生成。這是一個水平條形圖,它是通過將多個子圖相互堆疊而創建的。
plot 看起來像:
我快接近了,但我無法完全重現它。 plot的程序大致是這樣的:
make_subplot
到目前為止,我面臨的最大問題是我無法重復主 plot 中每個單獨子圖的標題。
這是我的代碼。 請注意,每個 plot 都有不同的標題:
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)
此代碼產生:
這是錯誤的多種方式:
有沒有辦法在 ploty-R 中生成這種圖形,還是我們僅限於 plotly-python?
您可以在layout
中使用帶有text
而不是標題的annotations
。 這是一個可重現的例子:
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
編輯:
您可以添加一個x
坐標以使標題位於左側,如下所示:
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,
x = 1.5),
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-20,使用reprex v2.0.2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.