首页 > 解决方案 > 在ggplotly中使用facet_wrap时如何使面板名称适合一行?

问题描述

当我使用 plotly 对图进行刻面时,它会导致面板名称与其下方的下一个图重叠。我希望面板名称适合该框,而不是与其下方的其他图重叠。我试图改变面板之间的间距,但这似乎不起作用。我宁愿面板名称适合一行而不是两行。这是我的代码:

library(ggplot2)
library(tidyverse)
library(plotly)

mtcars$cyl = sample(letters[1:5], 32, TRUE)
mtcars$cyl <- as.factor(mtcars$cyl)
mtcars$gear <- as.factor(mtcars$gear)


library(magrittr)
gg_facet_nrow <- function(p){
  num_panels <- length(unique(ggplot_build(p)$data[[1]]$PANEL)) # get number of panels
  num_cols <- ggplot_build(p)$layout$facet$params$ncol # get number of columns set by user
  num_rows <- wrap_dims(num_panels, ncol=num_cols)[1] # determine number of rows
}

p1 <- ggplot(mtcars, aes(mpg, wt)) +geom_line()+ facet_wrap( . ~ gear,  scale = "free_y", ncol = 1 ) + theme(panel.spacing = unit(1,"cm"))
p2 <- ggplot(mtcars, aes(mpg, wt)) + geom_line() + facet_wrap(vars(cyl, gear), scale = "free_y", ncol = 1) + theme(panel.spacing = unit(1,"cm")) 

he <- gg_facet_nrow(p1)
he1 <- gg_facet_nrow(p2)

ggplotly(p1, height = he *300)

ggplotly(p2, height = he1 * 300)

这是我的意思的图片: 在此处输入图像描述

有谁知道为什么会发生这种情况以及如何解决?

标签: rggplot2ggplotly

解决方案


推荐阅读