R-处理长标签 [英] R - Handle long labels in plotly

查看:94
本文介绍了R-处理长标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有ggplot2图的以下功能.该功能的一项功能是str_wrap函数调用,用于处理我拥有的很长的标签.

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

它在普通" R环境中运行良好,我想将其与plotly一起使用.因此,我添加以下代码行:

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).

如何解决此问题?

这是一个简单的例子:

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)

推荐答案

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

You can use plotly_build() to adjust the margins.

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

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.

使用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-处理长标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆