Search code examples
rbar-chartsweave

Change the width of a figure created with barplot()


When I use barplot, I cannot see the names of the bars if the names are too big. For example:

barplot(as.numeric(c(2, 4, 1, 6)), col = c("lightblue"), main="Barplot",
        names.arg=c("This is bar 1...1", "This is bar 1...2",
                    "This is bar 1...3", "This is bar 1...4"), 
        xpd=TRUE, las=1, lwd=1, cex.names=0.5)

When I use horiz=TRUE, I cannot see the names on the left:

barplot(as.numeric(c(2, 4, 1, 6)), col = c("lightblue"), main="Barplot", 
        names.arg=c("This is \nbar 2...1", "This is bar 2...2",
                    "This is bar 2...3", "This is bar 2...4"), 
        xpd=TRUE, las=1, lwd=1, horiz=TRUE, space=1)

Using a line break in names (e.g. "This is \nbar 2...1") or reducing text size with, e.g., cex.names=0.5 "solves" the problem but I would prefer to add space so that the names fit.

Is there any ability to change the width of the whole figure including the plot?


Solution

  • When horiz=FALSE (the default), one option is to plot the bar names perpendicular to the x-axis with las=2, and add height to the bottom margin to accommodate the length of the names. To add space to the margin, use par(mar=c(b, l, t, r)), where b, l, t, and r are numbers giving the number of lines width/height that you want the bottom, left, top, and right margins to be, respectively.

    For example:

    par(mar=c(15, 3, 3, 1)) # 15 line height for bottom margin
    barplot(c(2, 4, 1, 6), main="Barplot", las=2,
            names.arg=c("This is my first very long name",
                        "This is my second very long name",
                        "This is my third very long name",
                        "This is my fourth very long name"))
    

    enter image description here

    When horiz=TRUE, you can use las=1 and add space to the left margin instead:

    par(mar=c(3, 15, 3, 1))
    barplot(c(2, 4, 1, 6), main="Barplot", las=1, horiz=TRUE,
            names.arg=c("This is my first very long name",
                        "This is my second very long name",
                        "This is my third very long name",
                        "This is my fourth very long name"))
    

    enter image description here