可以用ggplot2固定轴边距吗?

Art*_*hur 6 r ggplot2 fixed-width shiny

我有一个由条形图组成的交互式显示器,该条形图显示了针对不同类别的选定统计信息。但是,ggplot2根据标签重新调整y轴的宽度,因此使条带在x方向上烦人地移动。参见示例:

library(shiny)
library(dplyr)
library(ggplot2)

shinyApp(
  ui = bootstrapPage(
    selectInput('statistic', label='Chose a statistic', choices=c('carat', 'depth', 'table', 'price')),
    plotOutput('plot')
  ),
  server = function(input, output) {
    output$plot <- renderPlot(
      diamonds %>%
        ggplot(aes(x=color, y=get(input$statistic))) +
        geom_bar(stat = 'sum') +
        theme(text = element_text(size=20), legend.position="none")
    )
  }
)
Run Code Online (Sandbox Code Playgroud)

如何确定y轴标签的宽度?(或者等价于绘图面板的宽度?)

我确实找到了相关的问题,但是所有问题都在静态上下文中解决,例如使用facets或with解决gtable

Mat*_*rde 5

一种方法是提供标签功能,通过在标签宽度上填充空格来标准化标签宽度。function(label) sprintf('%15.2f', label)会在左侧填充15个空格,并在数值上显示2个小数位。

library(shiny)
library(dplyr)
library(ggplot2)

shinyApp(
  ui = bootstrapPage(
    selectInput('statistic', label='Chose a statistic', choices=c('carat', 'depth', 'table', 'price')),
    plotOutput('plot')
  ),
  server = function(input, output) {
    output$plot <- renderPlot(
      diamonds %>%
        ggplot(aes(x=color, y=get(input$statistic))) +
        scale_y_continuous(labels=function(label) sprintf('%15.2f', label)) +
        geom_bar(stat = 'sum') +
        theme(text = element_text(size=20), legend.position="none")
    )
  }
)
Run Code Online (Sandbox Code Playgroud)

  • 没有我的数据很难复制,但是它来自字体“ theme”中的“ cause using`axis.text.y = element_text(family ='mono')`引起的” (5认同)