【问题标题】:R - Handle long labels in plotlyR - 在情节中处理长标签
【发布时间】:2016-12-08 17:02:49
【问题描述】:

我在ggplot2 绘图中具有以下功能。该函数的一个特点是调用str_wrap 函数来处理我拥有的很长的标签。

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)

【问题讨论】:

    标签: r plot plotly


    【解决方案1】:

    您可以使用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
    

    【讨论】:

    • 谢谢,它可以在 R 中工作,但我在 Shiny output$TheResponseRate &lt;- renderPlotly({ MyPlot &lt;- PlotResponseRate (EntryData = df) MyPlot &lt;- plotly_build(MyPlot) MyPlot $x$layout$margin$l &lt;- 180 }) 中有一个错误
    • 消息是“UseMethod 中的错误:ggplotly 没有适用于类“c('double', 'numeric')”的对象的方法。
    猜你喜欢
    • 2017-01-28
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    相关资源
    最近更新 更多