我尝试创建一个2x2的子图,每列中的两个图具有相同的y轴标题,如下所示:
即一个“标题”(这里称为注解,参见下文)用于左列(蓝色+绿色),一个用于右列(黄色+红色)。
我可以很容易地为每个图设置一个y轴标题,但我很难设置共享标题。我尝试使用注解,如下所示(这是用于渲染上面的图的代码):
if (!require("plotly")) install.packages("plotly")
library(plotly)
group <- c("a", "b", "c")
values <- c(0, 5, 10)
df <- data.frame(group, values)
plot <- df %>%
plot_ly() %>%
add_trace(x = ~group, y = ~values, type = "scatter", mode = "line") %>%
layout(yaxis = list(ticks = "outside"), xaxis = list(showline = TRUE))
plot
subdf1 <- subplot(plot, plot, nrows = 1, margin = 0.06)
subdf2 <- subplot(plot, plot, nrows = 1, margin = 0.06)
subdf <- subplot(subdf1, subdf2, nrows = 2, margin = 0.06) %>%
layout(annotations = list(list(x = -0.1, y = 0.5, text = "<b>First annotation</b>", xref = "paper", yref = "paper", xanchor = "center", yanchor = "center", showarrow = FALSE, textangle = -90, font = list(color = "black", size = 16)),
list(x = 0.48, y = 0.5, text = "<b>Second annotation</b>", xref = "paper", yref = "paper", xanchor = "center", yanchor = "center", showarrow = FALSE, textangle = -90, font = list(color = "black", size = 16))))
subdf
我对这种方法的主要不满是,当调整图的大小时,注解(主要是第一个,在x轴位置的负范围内)绕x轴移动。
相同的情节,但更广泛:
我使用xref = "paper"
,因为我认为它意味着整个绘图区域,即整个白色背景,但在这种情况下,我的注解不会消失(也不会变成负数,但我可能没有正确地考虑这一点)。我确实尝试使用xref = x
,但它不会变成负数,而是将数据向右推。
总而言之,有两个问题:
- 是否有一种本地方式可以为子图共享轴标题?
- 如果没有,在调整子图大小时,是否有办法确保注解与图和轴保持在相同的相对位置?
2条答案
按热度按时间dojqjjoe1#
如果你不想使用plotly,你可以直接使用ggplot中的faceting来完成,它可能需要你把数据重新排列成整齐的格式,但是在绘图时提供了很大的灵活性!
shstlldc2#
您可以在两个
subplots
的每个layout
中创建一个单独的标题,然后使用titleY
将它们组合起来,如下所示:创建于2023年1月23日,使用reprex v2.0.2
将
margin
更改为layout
:创建于2023年1月23日,使用reprex v2.0.2