使用 ggplotly 时会忽略 str_wrap(但不是 ggplot)

问题描述 投票:0回答:1

我想将下面的图例的文本换行,它与

ggplot
:

一起使用
library(tidyverse)
library(ggtext)
library(plotly)

df <- data.frame(xx = c(0, 3),
                 yy = c(0, 1))

df_text <- data.frame(start = c(0, 1, 2),
                      end = c(1, 2, 3),
                      heading_bold = c("title 1", "title 2", "title 3"),
                      normal_text = c("i want this to be normal text title 1 but it is also a very long title that i want to wrap",
                                      "i want this to be normal text title 2 but it is also a very long title that i want to wrap",
                                      "i want this to be normal text title 3 but it is also a very long title that i want to wrap")) %>% 
  mutate(merged_text = paste0("**",heading_bold,"**: ", normal_text)) 

pp <- ggplot(df, aes(x = xx, y = yy)) +
  geom_rect(data = df_text,
            aes(xmin = start,
                xmax = end,
                fill = merged_text,
                ymin = 0,
                ymax = 1),
            inherit.aes = FALSE) +
  scale_fill_viridis_d(option = "A", name = "Legend", 
                       limits = unique(df_text$merged_text), direction = -1, 
                       labels = function(x) str_replace_all(str_wrap(x, width = 30), "\\n", "<br>")) +
  theme(legend.text = element_markdown())
pp

enter image description here

但是迷失了

ggplotly

ggplotly(pp)

enter image description here

我确信有一种聪明的方法可以应用

css
/
html
样式来实现此目的(无需再次写出完整的图例文本)-有什么想法吗?

谢谢

html css r ggplotly ggtext
1个回答
0
投票

这里发生的事情实际上是当您转换为

plotly
对象时,新行会丢失。你可以在这里看到这个:

ggpl <- ggplotly(pp)
ggpl$x$data[[1]]$name
# [1] "**title 1**: i want this to be normal text title 1 but it is also a very long title that i want to wrap"

如您所见,您忠实添加的

<br>
块已经消失。我认为这可能与
plotly
转义 html 有关,但即使您使用
htmltools::HTML("<br>")
,也会发生同样的事情。

幸运的是,一旦您知道问题是什么,就很容易解决:

add_line_breaks <- function(ggplotly_object, width = 30) {
    ggplotly_object$x$data <- lapply(
        ggplotly_object$x$data,
        \(l) {
            l$name <- str_replace_all(str_wrap(l$name, width = width), "\\n", "<br>")
            l
        }
    )
    ggplotly_object
}

然后您可以按如下方式使用它:

pp |>
    ggplotly() |>
    add_line_breaks() 

输出:

The plot with line breaks

© www.soinside.com 2019 - 2024. All rights reserved.