ggplotly在标签中带有长名称

时间:2020-05-02 14:40:27

标签: r ggplot2 r-plotly 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的{​​{1}}版本中不会出现此问题。

任何帮助将不胜感激

谢谢

1 个答案:

答案 0 :(得分:2)

看起来您偶然发现了ggplotly中的错误(也许您应该在github上提出问题)。我看了一下源代码。问题是,ggplotly在计算边距时未考虑刻度标签中的换行符。因此,边距设置得太宽。如果使用plotly进行绘图,则不会出现此问题。但是,作为一种简单的解决方法,您可以通过添加布局选项automargin来强制margin = list(l = 0)来完成其工作:

ggplotly(p) %>%
  layout(
    margin = list(l = 0)
  )

其结果如下:

enter image description here

相关问题