Is it possible to fix axis margin with ggplot2?

前端 未结 1 726
有刺的猬
有刺的猬 2020-12-10 17:39

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 de

相关标签:
1条回答
  • 2020-12-10 18:21

    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")
        )
      }
    )
    
    0 讨论(0)
提交回复
热议问题