Chapter 4 Default Bar plots in R

Basic bar plots:

par(mfrow=c(2,1), mar=c(3,3,1,0)+.5, mgp=c(1.6,.6,0))
x<-c(1:5)
barplot(x,col="#67E300")
barplot(x,horiz=TRUE,col="#F16D95")

Change group names:

barplot(x, names.arg = c("1", "2", "3","4","5"), col="lightblue")

Change color:

par(mfrow=c(2,2), mar=c(3,3,1,0)+.5, mgp=c(1.6,.6,0))
x<-c(1:5)
# Change border and fill color using one single color
barplot(x, col = "white", border = "steelblue")
# Change the color of border.
#  Use different colors for each group
barplot(x, col = "white",
        border = c("#999999", "#E69F00", "#56B4E9"))
# Change fill color : single color
barplot(x, col = "steelblue")
# Change fill color: multiple colors
barplot(x, col = c("#999999", "#E69F00", "#56B4E9"))

Change main title and axis labels:

# Change axis titles
# Change color (col = "orange") and remove frame
x<-c(1:5)
barplot(x, main = "Number of 1 to 5",
        xlab = "Number", ylab = "Number", col="orange")

Stacked bar plots:

Example-1:

barplot(VADeaths,
         col = c("lightblue", "mistyrose", "lightcyan", 
                 "lavender", "cornsilk"),
        legend = rownames(VADeaths))

Stacked bar plots:

Example-1:

barplot(VADeaths,
         col = c("lightblue", "mistyrose", "lightcyan", 
                 "lavender", "cornsilk"),
        legend = rownames(VADeaths))

Example-2:

# Stacked Bar Plot with Colors and Legend
counts <- table(mtcars$vs, mtcars$gear)
barplot(counts, main="Car Distribution by Gears and VS",
  xlab="Number of Gears", col=c("#FF7800","#5EC4CD"),
  legend = rownames(counts))

Grouped bar plots:

Example-1:

barplot(VADeaths,
         col = c("lightblue", "mistyrose", "lightcyan", 
                 "lavender", "cornsilk"),
        legend = rownames(VADeaths),beside = TRUE)

Example-2:

  • box.lty = 0: Remove the box around the legend

  • cex = 0.8: legend text size

# Define a set of colors
my_colors <- c("lightblue", "mistyrose", "lightcyan", 
                 "lavender", "cornsilk")
# Bar plot
barplot(VADeaths, col = my_colors, beside = TRUE)
# Add legend
legend("topleft", legend = rownames(VADeaths), 
       fill = my_colors, box.lty = 0, cex = 0.8)

Example-3:

# Grouped Bar Plot
counts <- table(mtcars$vs, mtcars$gear)
barplot(counts, main="Car Distribution by Gears and VS",
  xlab="Number of Gears", col=c("mistyrose","lightblue"),
  legend = rownames(counts), beside=TRUE)

Note: If you need more formatting, see the 3-Standard R graphs formatting.