请考虑以下简单示例。有没有一种方法可以格式化绘图工具提示,使长文本标签在框中可见,而不是这个荒谬的矩形会截断值?
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")
答案 0 :(得分:2)
我很确定,某个地方存在更优雅的解决方案。我可以建议您像每个n
字符一样休息一下。 https://stackoverflow.com/a/2352006/9300556有一个不错的解决方法:
gsub('(.{1,90})(\\s|$)', '\\1\n', s)
它将字符串“ s”分成最多90个字符的行(不包括 换行符“ \ n”,但包括单词间空格), 除非单词本身超过90个字符,否则该单词 本身将占据整条线。
所以我们只需要在gsub()
美学中添加ggplot
:
p <- ggplot(df, aes(x,y,
text = gsub('(.{1,20})(\\s|$)', '\\1\n', z))) +
geom_point()
ggplotly(p, tooltip = "text")
更新
这是@Rich Pauloo的评论中更为优雅的解决方案。在这种情况下,您的琴弦也大部分会被填充(但实际上会自动对齐)。但是,填充取决于绘图分辨率和标签位置。
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")