[英]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.