title: Automatic adjustment of margins in horizontal bar chart
body: <p>I need to produce a series of horizontal grouped bar charts. The barplot function does not automatically adjust the margins of the plot, therefore the text gets cut off.</p>
  
  <pre><code>  graphics.off()      # close graphics windows
     test &lt;- matrix(c(55,65,30, 40,70,55,75,6,49,45,34,20), 
                    nrow =3 , 
                 ncol=4, 
                 byrow=TRUE,
                 dimnames = list(c("Subgroup 1", "Subgroup 2", "Subgroup 3"),
                                 c(
                                   "Category 1 Long text",
                                   "Category 2 very Long text",
                                   "Category 3 short text",
                                   "Category 4 very short text"
                                   )))
    barplot(test, 
         las=2,
         beside = TRUE,
         legend=T,
         horiz=T)
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/ekapj.png" alt="enter image description here"></p>
  
  <p>I can't find an option to automatically move the plot further to the right, the way R dotchart function does it ( (barchart procedure in SAS adjusts the margins automatically as well). Obviously, I can always adjust the margins manually using par function.</p>
  
  <pre><code>  par(mar=c(5.1, 13 ,4.1 ,2.1))
  </code></pre>
  
  <p>will move the plot to the right </p>
  
  <p><img src="https://i.stack.imgur.com/6JzXa.png" alt="enter image description here"></p>
  
  <p>Is there an option to move the plot to the right (i.e. adjust the margins) automatically depending on the length of the text? </p>
  
  <p>I can think of 2 related appproaches to do it programmatically:
  1) Calculate the length of the longest text string and accordingly adjust the left margin 
  2) Create a dotchart plot for the data, somehow capture the margins and use the same margins in bar chart.</p>
  
  <p>Is there an easier way to do it?
  Thanks!</p>