简体   繁体   中英

How to fit a text tooltip in the screen (ggplotly R)

When generating a plotly geom_point() plot with a tooltip that contains a long description, the package's standard is to show the text in a single line. The issue with that is that it does not fit in the screen. How is it possible to break the line, in a way that it can be read?

 library(tidyverse)
 library(plotly)


bd <- data.frame(Freq = c(1, 2, 3),
                     Criticality = c("A", "B", "C"),
                     Status = c("alpha", "beta", "alpha"),
                     Plant = c(1, 2, 1),
                     Description = c("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                                      "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
                                      "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"))

    g <- bd %>% 
       ggplot(aes(x = Freq, y = Criticality)) +
      geom_point(aes(shape = Status, col = Plant, text = Description)) +
      geom_jitter(aes(shape = Status, col = Plant, text = Description)) +
      guides(size = FALSE)

    ggplotly(g, tooltip = c("Description"))

Currently, I get the following error message but it does not generate any problem.

Warning: Ignoring unknown aesthetics: text

If the strings have no spaces, I would use the method suggested by Ben. If there are spaces, you can use str_wrap()

library(tidyverse)
library(plotly)

bd <-
  tibble(
    Freq = c(1, 2, 3),
    Criticality = c("A", "B", "C"),
    Status = c("alpha", "beta", "alpha"),
    Plant = c(1, 2, 1),
    Description = paste(sentences[1:3], collapse = " "),
    tooltip = str_wrap(Description, 30)
  )

g <- bd %>% 
  ggplot(aes(x = Freq, y = Criticality)) +
  geom_point(aes(shape = Status, col = Plant, label = tooltip)) +
  geom_jitter(aes(shape = Status, col = Plant, label = tooltip)) +
  guides(size = FALSE)

ggplotly(g, tooltip = c("tooltip"))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM