r - 标签中带有长名称的ggplotly
问题描述
我有长名称的数据,我想使用ggplotly
.
那是我的代码:
library(ggplot2)
library(plotly)
temp<-data.frame(x=c("longgggggggggggggggggggggggg_nameeeeeeeeeeeeeee1", "longggggggggggggggggggggggggg_nameeeeeeeeeeeeeee2"),
y=c(5,10))
break_str<-function(str,n){
if(nchar(str)<=n)
return(str)
ans<-""
for(i in 1:ceiling(nchar(str)/n)){
if(i<ceiling(nchar(str)/n)){
ans<-paste0(ans,substr(str,start=((i-1)*n+1),stop=min(i*n,nchar(str))),"\n")
} else{
ans<-paste0(ans,substr(str,start=((i-1)*n+1),stop=min(i*n,nchar(str))))
}
}
return(ans)
}
p <- ggplot(temp, aes(x=x, y=y)) +
labs(x="x",y="y") + geom_bar(stat="identity") + coord_flip() +
scale_x_discrete(labels = function(x) lapply(x,function(str){break_str(str,10)}))
ggplotly(p)
正如你所看到的,我使用了一个自定义break_str
函数,它的工作原理类似于stringr::str_wrap
但它仍然不会删除图中的边距。
这个问题ggplot
在p
.
任何帮助,将不胜感激
谢谢
解决方案
看起来你偶然发现了一个错误ggplotly
(也许你应该在github上提出一个问题)。我查看了源代码。问题是ggplotly
在计算边距时没有考虑刻度标签中的换行符。因此,边距设置得太宽。如果您使用plotly
. 但是,作为一种简单的解决方法,您可以automargin
通过添加布局选项来强制完成其工作,margin = list(l = 0)
如下所示:
ggplotly(p) %>%
layout(
margin = list(l = 0)
)
这导致了这个情节:
推荐阅读
- google-chrome - 在 Chrome 控制台中输入的值下方出现的字符是什么?
- antlr - exitXXX 函数如何知道匹配了什么规则
- javascript - 如何在我的网站上使用多个模式?
- java - Hamcrest:测试一个 Iterable 是否包含另一个 Iterable 的所有元素
- node.js - 使用 npm 和 grunt 为 OpenUI5 配置 http 服务器时设置正确的路径
- ios - 如果满足条件,则替换 Set 中的元素
- angular - 如何为垫卡添加垫分页器?
- c# - .NET Core 与 XML 版本 1.1 的兼容性
- sql - Oracle SQL - 根据两列选择重复项
- javascript - 如何使用 chart.js 组合图表中的所有值?