Is it possible to fix axis margin with ggplot2?

こ雲淡風輕ζ 提交于 2019-11-27 06:20:30

问题


I have an interactive display consisting of a bar chart that shows a selected statistic for different categories. However, ggplot2 readjusts the y-axis width depending on the labels, and hence makes the bars annoyingly move on the x-direction. See exemple:

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

How can I fix the width of the y-axis label? (or equivalently the width of the plotting panel?)

I did find related questions, but all were solved in a static context, for instance with facets or with gtable.


回答1:


One way would be to provide a label function that normalizes the label widths by padding them with spaces. function(label) sprintf('%15.2f', label) would pad with 15 spaces on the left and print the numeric value with 2 decimal places.

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


来源:https://stackoverflow.com/questions/34677551/is-it-possible-to-fix-axis-margin-with-ggplot2

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