r - plotly R : setting the spacing between axis label and axis ticks labels

标签 r plotly

除了更改边距之外,还有什么方法可以设置轴标签和轴刻度标签之间的间距吗?

示例图:

plot_ly(mtcars, x = ~ wt, y = ~ paste0(hp, '0000'))

如上面的示例图中所示,y 轴的标题与该轴的刻度标签重叠。有没有办法设置它们之间的间距?

最佳答案

推荐的解决方案

plotly v4.9.2您可以使用新的 standoff layout attribute其中

Sets the standoff distance (in px) between the axis labels and the title text The default value is a function of the axis tick labels, the title font.size and the axis linewidth. Note that the axis title position is always constrained within the margins, so the actual standoff distance is always less than the set or default value. By setting standoff and turning on automargin, plotly.js will push the margins to fit the axis title at given standoff distance.

示例:

plotly::plot_ly(mtcars, x = ~ wt, y = ~ paste0(hp, '0000')) %>%
  plotly::layout(yaxis = list(title = list(text = "Gross horsepower",
                                           standoff = 40L)))

enter image description here

<小时/>

过时的解决方法

问题

增加左边距as @Codutie suggests in his answer仅在一定程度上有帮助(至少在plotly v4.7.1+中)。左侧 150 像素边距的大部分都是浪费的空间,如下面的屏幕截图所示: enter image description here

生成上述绘图的 R 代码(来自 @Codutie):

library(plotly)

plot_ly(mtcars, x = ~ wt, y = ~ paste0(hp, '0000')) %>%
  layout(margin = list(l = 150, r = 20, b = 10, t = 10))

由于 Plotly 的目标是响应式,所以它会自动进行很多布局缩放 - 恕我直言,这通常是一件好事,因为您不必花太多时间来获得漂亮的图表。当然,Plotly 自动缩放的结果并不总是完美的或完全符合您想要实现的效果,这就是为什么 there are plenty of dedicated (layout) attributes让你操纵 plotly 的某些方面。 不幸的是,没有属性可以设置轴标签和轴本身之间的距离(或轴刻度标签)。

解决方案(解决方法)

相反,您可以依靠以下解决方法通过设置适当的 y 轴标题字符串来控制轴与其标签之间的距离:

plot_ly(mtcars, x = ~ wt, y = ~ paste0(hp, '0000')) %>%
    layout(margin = list(l = 150, r = 20, b = 10, t = 10),
           yaxis = list(title = paste0(c(rep("&nbsp;", 20),
                                         "Gross horsepower",
                                         rep("&nbsp;", 20),
                                         rep("\n&nbsp;", 3)),
                                       collapse = "")))

这会导致: enter image description here

y 轴标题组件的说明:

  • rep("\n ", 3):这是增加距离技巧的主要部分 - 只需添加实际标题后缀(“总马力”) 带有换行符和不间断空格。
  • rep(" ", 20):这是确保 Plotly 的自动缩放不会再次干扰的额外措施 - 将实际标题包装在 40 个不间断空格中(可能更多/当然更少)。否则,一旦绘图高度足够大以“物理上”允许,文本总马力就会被放置在两个轴刻度之间 - 这会有点挫败我们手动设置距离的尝试,因为我们会必须使用更大的换行符-不间断空格组合来再次获得相同的距离,更重要的是,距离将取决于绘图高度。在上面的图中,这实际上并不是必要的,因为您需要显示高度超过 1000 像素的绘图才能达到该临界点,因此需要尽可能多的 y 轴刻度。

关于r - plotly R : setting the spacing between axis label and axis ticks labels,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43229013/

相关文章:

r - 根据类别分析多项选择题和多项选择答案

r - 如何从 R 绘图图中获取坐标

css - django-plotly-dash div 大小太小,不会改变

r - 如何调整标题空间并在 r 中绘图

javascript - Shiny and rhandsontable - 基于列总和的条件单元格/列格式

r - 使用 ranger R 包计算 Brier 分数和综合 Brier 分数

r - 为什么在具有许多组的大型数据帧上拆分效率低下?

r - 多变量 tidyr 旋转

Power BI 中的 Python Plotly

r - 使用 plotly rstudio 从数据框创建漏斗图