2016-12-08 84 views
1

我有以下功能ggplot2情节。该函数的一个功能是调用str_wrap函数来处理我拥有的非常长的标签。R - 剧情处理长标签

PlotResponseRate <- function(EntryData) 
{ 
    PlotData <- as.data.frame(apply(X = EntryData, MARGIN = 2, 
              function(x) round(length(which(!is.na(x)))/length(x)*100))) 
    colnames(PlotData) <- "TheData"  
    PlotData$TheLabel <- factor(str_wrap(colnames(EntryData), width = 30), 
            levels = unique(str_wrap(colnames(EntryData), width = 30))) 

    Graphe <- ggplot(data = PlotData, aes(x = TheLabel, y = TheData)) + 
    geom_bar(stat = "identity", fill = "red", width = 0.8) + 
    coord_flip() + 
    labs(title = "Response rate") 
    } 

它工作正常,在“普通” R环境在,我想与plotly使用它。因此,我添加以下代码行:

PlotData$TheLabel <- gsub(pattern = "\n", replacement = "\n<br>", PlotData$TheLabel) 

这似乎工作,但还有一个问题:在图中左侧的空间太宽(我不知道,但它看起来是与长标签相同的空间)。

如何解决此问题?

下面是一个简单的例子:

library(stringr) 
library(ggplot2) 
library(plotly) 

a <- c(1, 2, 2, 2, NA, 1, 2, 2, 1) 
b <- c(2, 1, 2, NA, 2, NA, 1, NA, 1) 
df <- data.frame(a, b) 

colnames(df) <- c("This Is A Long Answer To A Long Question Label For The First Question", 
        "This Is A Long Answer To A Long Question Label For The Second Question") 

TheGgplot2Plot <- PlotResponseRate(df) 

ThePlotlyPlot <- ggplotly(TheGgplot2Plot) 
print(ThePlotlyPlot) 

enter image description here

回答

2

您可以使用plotly_build()调整页边距。

这个通用函数创建发送到plotly.js为 渲染列表对象。使用此功能可用于覆盖ggplotly/plot_ly提供的默认值 或调试渲染错误。

使用plotly_build生成列表对象:

ThePlotlyPlot <- plotly_build(TheGgplot2Plot) 

景观结构:

str(ThePlotlyPlot) 

..$ layout :List of 13 
    .. ..$ margin  :List of 4 
    .. .. ..$ t: num 57.7 
    .. .. ..$ r: num 7.31 
    .. .. ..$ b: num 54.1 
    .. .. ..$ l: num 481 

调整边距:

ThePlotlyPlot$x$layout$margin$l <- 100 

enter image description here

+0

谢谢,它的工作原理中的R,但是我有光泽'输出$ TheResponseRate <错误 - renderPlotly({ MyPlot < - PlotResponseRate(EntryData = DF) MyPlot < - plotly_build(MyPlot) MyPlot $ X $布局$余量$ l < - 180 })' – Kumpelka

+0

消息是“Error in UseMethod:no ggplotly'方法适用于类”c('double','numeric')“的对象。 – Kumpelka