首页 > 解决方案 > 标签中带有长名称的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但它仍然不会删除图中的边距。

这个问题ggplotp.

任何帮助,将不胜感激

谢谢

标签: rggplot2r-plotlyggplotly

解决方案


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

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

这导致了这个情节:

在此处输入图像描述


推荐阅读