Facet_Wrap 标题与 ggplotly 中的 y-axis 重叠?

Facet_Wrap title overlapping with y-axis in ggplotly?

我目前正在使用 facet_wrap 将数据 (html) 编织到 Rmarkdown 文档中。我希望使用 facet_wrap 和 ggplot 来显示此数据。

这是数据在 ggplot 中的样子(不是 plotly):

但是,当我使用 plotly 时,每个情节的标题都与 y-axis 相交,这使得解释性变得困难

这是第一个不使用 plotly 的绘图的代码

plot <-  ggplot(dataframe, aes(x = week, y = measure))+
  geom_line(size = 1.25, aes(color = "orange"))+
  geom_point(size = 1.50)+
  theme_economist()+
  geom_smooth(method = 'auto', se = FALSE, size = .50)+
  scale_x_continuous(breaks=seq(0,13,1))+
  scale_y_continuous(labels = scales::dollar_format(scale = .0001, suffix = "K"))+
  facet_wrap(vars(category), scales = "free", ncol = 3, nrow = 6)+
  theme(legend.position = "none")+
  ggtitle('Title')+
    theme(
    panel.grid.major = element_line(linetype = "dotted"),
    axis.title.x = element_text( size = 10, margin=margin(30,0,0,0)),
    axis.title.y = element_text( size = 10, margin=margin(0,30,0,0)),
    axis.text = element_text( size = 10),
    plot.title = element_text( size = 14, margin=margin(0,0,35,0), hjust = 0.5),
    panel.background = element_rect(fill = NA),
    strip.text = element_text(size=10)
  )

然后这就是我将它转换为 plotly

ggplotly(plot)

一些随机数据:

require(stats)
r <- function(x) {abs(as.numeric(arima.sim(n=x, list(order=c(1,0,0),ar=0.95)))+10)}
dataframe = data.frame(week = rep(1:13,6), measure = r(13*6), category = rep(as.character(1:6),each=13))

虽然我无法重现重叠的 y-axis 标签,但您可以通过在 theme() 中设置 panel.margin.ypanel.margin.x 来设置分面图之间的边距:

plot <- ggplot(dataframe, aes(x = week, y = measure))+
  geom_line(size = 1.25, aes(color = "orange"))+
  geom_point(size = 1.50)+
  theme_economist() + 
  geom_smooth(method = 'auto', se = FALSE, size = .50)+
  scale_x_continuous(breaks=seq(0,13,1))+
  scale_y_continuous(labels = scales::dollar_format(scale = .0001, suffix = "K"))+
  facet_wrap(vars(category), scales = "free", ncol = 3, nrow = 6)+
  theme(legend.position = "none")+
  ggtitle('Title')+
    theme(
    panel.grid.major = element_line(linetype = "dotted"),
    axis.title.x = element_text( size = 10, margin=margin(30,0,0,0)),
    axis.title.y = element_text( size = 10, margin=margin(0,30,0,0)),
    axis.text = element_text( size = 10),
    plot.title = element_text( size = 14, margin=margin(0,0,35,0), hjust = 0.5),
    panel.background = element_rect(fill = NA),
    strip.text = element_text(size=10), panel.margin.x = unit(1,"lines"), panel.margin.y = unit(0,"lines")
  )
ggplotly(plot)

您可以微调边距以适合您的情节。

之前:

> ggplotly(plot)

之后:

> ggplotly(plot)