Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to fix axis margin with ggplot2?

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.

like image 664
Arthur Avatar asked Jan 08 '16 12:01

Arthur


People also ask

How do I fix margins in ggplot2?

Increase margins In order to modify the plot margins set the margin function inside the plot. margin component of the theme function. The margins are measured with points ( "pt" ), but you can use other unit measure in the unit argument, like centimeters.

How do I change the margins in R plot?

You can adjust the size of the margins by specifying a margin parameter using the syntax par(mar = c(bottom, left, top, right)) , where the arguments bottom , left … are the size of the margins. The default value for mar is c(5.1, 4.1, 4.1, 2.1).

How do I change the Y axis scale in ggplot2?

Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.


1 Answers

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")
    )
  }
)
like image 118
Matthew Plourde Avatar answered Sep 28 '22 07:09

Matthew Plourde