Is it possible to fix the axis boundary with ggplot2?

I have an interactive display consisting of a histogram that displays the selected statistics for different categories. However, it ggplot2reconfigures the width of the y axis depending on the labels and, therefore, makes annoying movements of the bars along the x axis. See an example:

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 equivalent to the width of the build panel?)

I found related questions, but they were all resolved in a static context, for example with faces or with gtable.

+3
source share
1 answer

- , , . 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")
    )
  }
)
+3

Source: https://habr.com/ru/post/1691805/


All Articles