R - Handle long labels in plotly

孤街浪徒 提交于 2019-12-24 09:48:41

问题


I have the following function with ggplot2 plot. One feature of the function is the str_wrap function call to handle the very long labels I have.

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") 
  }

It works fine in the "ordinary" R environnement and I want to use it with plotly. Therefore, I add the following line of code :

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

It seems working but there is still a problem : the space in the left of the plot is too wide (I'm not sure but it looks like it is the same space that the long label would do).

How to get around this behavior ?

Here is a simple example :

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)


回答1:


You can use plotly_build() to adjust the margins.

This generic function creates the list object sent to plotly.js for rendering. Using this function can be useful for overriding defaults provided by ggplotly/plot_ly or for debugging rendering errors.

Use plotly_build to generate the list object:

ThePlotlyPlot <- plotly_build(TheGgplot2Plot)

View the structure:

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

Adjust the margins:

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



来源:https://stackoverflow.com/questions/41044915/r-handle-long-labels-in-plotly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!