使用 ggplotly() 时如何保留字幕字幕、ggplotly

2023-09-06 08:15:20 作者:罂粟花很毒╯

我有这张图表.

g <- retention_cohorts %>% 
  ggplot(aes(relative_week, round(percent,2), label=relative_week)) + 
  geom_line() +
  scale_y_continuous(labels = percent) +
  scale_x_continuous(breaks = seq(1,24,4),
                     labels = seq(1,6)
  ) +
  geom_text(nudge_y = .02) +
  labs(
    title = "Purchasing Retention Analysis",
    subtitle = "Customers who order at least one item each week",
    y = "Customers with at least One Purchase",
    x = "Relative Month"
  ) + theme_light()

这是一个很棒的图表,我想让它具有交互性.当我使用 ggplotly(g) 时,它几乎完美地重新创建了它,只是它删除了字幕.在创建 plotly 实体后,有没有办法强制它保留字幕或添加新文本作为字幕?

It's a great chart and I want to make it interactive. When I use ggplotly(g), it recreates it almost perfectly except that it drops the subtitle. Is there a way to force it to keep the subtitle or to add new text as a subtitles after the plotly entity has been created?

推荐答案

这对我有帮助,带有ggplotly的字幕.似乎任何添加到 ggplot 的文本(例如注释或字幕)都必须放在 ggplotly 函数之后放入布局函数中.

This helped me, Subtitles with ggplotly. Seems any text such as annotations or subtitles added to ggplot must be put after the ggplotly function into a layout function.

plot <- retention_cohorts %>% 
  ggplot(aes(relative_week, round(percent,2), label=relative_week)) + 
  geom_line() +
  scale_y_continuous(labels = percent) +
  scale_x_continuous(breaks = seq(1,24,4),
                     labels = seq(1,6)) +
  geom_text(nudge_y = .02) +
  labs(y = "Customers with at least One Purchase",
       x = "Relative Month") + 
  theme_light()

ggplotly(plot) %>%
  layout(title = list(text = paste0('Purchasing Retention Analysis',
                                    '<br>',
                                    '<sup>',
                                     'Customers who order at least one item each week','</sup>')))