以图形方式格式化工具提示以获取长文本标签 [英] Format tooltip in plotly for long text labels

查看:128
本文介绍了以图形方式格式化工具提示以获取长文本标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的简单示例.有没有一种方法可以格式化绘图工具提示,以使长文本标签在框中可见,而不是这个荒谬的矩形会截断值?

Consider the simple example below. Is there a way to format the plotly tooltip such that the long text labels are visible in a box, rather than this absurd rectangle that cuts off values?

library(ggplot2); library(plotly)

df <- data.frame(x = 1:10, y = 1:10, z = rep("the longggggggggggggggggggggggggggggestttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt labelllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll you can imagineeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", 10))

p <- ggplot(df, aes(x,y,label=z)) + geom_point()
ggplotly(p, tooltip = "label")

推荐答案

我很确定,某个地方存在更优雅的解决方案.我可以建议您像每个n字符一样休息一下.从 https://stackoverflow.com/a/2352006/9300556 有一个不错的解决方法:

I'm pretty sure, that the more elegant solution somewhere exists. I can just suggest you to put a break like every n character. There is a nice workaround from https://stackoverflow.com/a/2352006/9300556:

gsub('(.{1,90})(\\s|$)', '\\1\n', s)

它将字符串"s"分成最多90个字符的行(不包括 换行符"\ n",但包括单词间的空格), 除非单词本身超过90个字符,否则该单词 本身将占据整条线.

It will break string "s" into lines with maximum 90 chars (excluding the line break character "\n", but including inter-word spaces), unless there is a word itself exceeding 90 chars, then that word itself will occupy a whole line.

所以我们只需要在ggplot美学中添加gsub():

So we just need to add gsub() into ggplot aesthetics:

p <- ggplot(df, aes(x,y,
            text = gsub('(.{1,20})(\\s|$)', '\\1\n', z))) +
  geom_point()

ggplotly(p, tooltip = "text")

更新

这是@Rich Pauloo的评论中的一种更优雅的解决方案.在这种情况下,您的琴弦也大部分会被填充(但实际上会自动对齐).但是,填充取决于绘图分辨率和标签位置.

Here is a more elegant solution from the comments by @Rich Pauloo. In this case your strings also will be mostly left padded (but actually auto-aligned). However, the padding depends on plot resolution and label location.

library(stringr)

p <- ggplot(df,
            aes(x, y,
                text = stringr::str_wrap(
                  string = z,
                  width = 20,
                  indent = 1, # let's add extra space from the margins
                  exdent = 1  # let's add extra space from the margins
                ))) +
  geom_point()

ggplotly(p, tooltip = "text")

这篇关于以图形方式格式化工具提示以获取长文本标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆