Barplot in R Programming

The Barplot or Bar Chart in R Programming is handy to compare the data visually. By seeing this R barplot or bar chart, One can understand, Which product is performing better compared to others. For example, If we want to compare the sales between different product categories, product color, we can use this R bar chart.

Let us see how to Create a R Bar Chart, Format its color, borders, adding legions, creating stacked bar Chart, and Juxtaposed barplot in R Programming language with an example.

R Barplot Syntax

The syntax to draw the bar chart or barplot in R Programming is

barplot(height, name.args = NULL, col = NULL, main = NULL)

and the complex syntax behind this bar chart is:

barplot(height, width = 1, space = NULL, name.args = NULL, 
        legend.text = NULL, beside = FALSE, horiz = FALSE, 
        density = NULL, angle = 45, col = NULL, border = par("fg"), 
        main = NULL, sub = NULL, xlab = NULL, ylab = NULL, 
        xlim = NULL, ylim = NULL, xpd = TRUE, log = "", 
        axes = TRUE, axisnames = TRUE, cex.axis = par("cex.axis"), 
        cex.names = par("cex.axis"), inside = TRUE, plot = TRUE, 
        axis.lty = 0, offset = 0, add = FALSE, args.legend = NULL,…)

There are many arguments supported by the barplot in R programming language. The following are the most used arguments in the real-time R bar chart:

  • height: You can specify either a Vector or a Matrix of values. If it is a Vector, the R bar chart created with a sequence of rectangular bars, and each bar height depends upon the vector value. And if the height is a Matrix of values and beside is FALSE, each matrix column represents the bar, and the row values create stacked sub bars. If beside is TRUE, and height is a Matrix of values then each matrix column represent the R Juxtaposed bar.
  • width: It is optional, but you can use this to specify the width of a bar in an R bar chart.
  • space: Please specify the amount of space you want to the left before each bar of R barplot. If the height is a Matrix of values and beside is TRUE, you have to pass two values to space argument, where the 1st value to provide space between the same group bars, and the 2nd value is space between the different columns (groups)
  • names.args: Please specify a Vector of names you want to plot below each bar or group of bars in an R bar chart. If we omit this argument, then the R bar chart takes the names from columnames if it is a matrix, or the names attribute of height if it is a vector.
  • text: Please specify a Vector of text used to construct the legend for the bar chart, or a Boolean value indicating whether you want to include the legend or not.
  • beside: It is a Boolean argument. If it is FALSE, the height columns portrayed as stacked bars in R, and if it is TRUE, the columns portrayed as Juxtaposed bars.
  • horiz: It is a Boolean argument. If it is FALSE, the bars drew vertically. If it is TRUE, bars drew horizontally.
  • density: Please specify the shading lines density (in lines per inch). By default, it is NULL, which means no shading lines.
  • angle: You can assign the slope of shading lines using this argument.
  • col: Please specify the vector of colors you want to use for your barplot in R. By default, it uses a set of 6-pascal colors.
  • border: Please specify the color you want to add to the borders. If you use border = NA, then borders omitted.
  • main: You can provide the Title for your R bar chart.
  • sub: You can provide the subtitle (if any) for your bar chart.
  • xlab: Please specify the label for the R barplot X-Axis
  • ylab: Please specify the label for the Y-Axis
  • xlim: This argument can help you to specify the limits for the X-Axis
  • ylim: This argument can help you to specify the R barplot Y-Axis limits
  • xpad: It is a Boolean argument. Do you want to allow the bars outside the region?
  • log: You have to specify a character string of three options. If X-Axis is to be logarithmic then “x”, If Y-Axis is to be logarithmic “y”, if both X-Axis and Y-Axis are to be logarithmic, then specify either “xy” or “yx”
  • axes: It is a Boolean argument. If it is TRUE, a vertical (or horizontal, if horiz = TRUE) axis is drawn.
  • axisnames: It is a Boolean argument. If it is TRUE, and if there are arg, the other axis is drawn (with lty = 0) and labeled in R barplot.
  • axis: Expansion factor for numeric axis labels.
  • names: Expansion factor for bar labels.
  • inside: It is a Boolean argument. If it is TRUE, the lines which divide adjacent bars drew. We have to use this argument when space = 0
  • plot: It is a Boolean argument. If it is FALSE, nothing plotted
  • lty: It is a graphical parameter, which applied to the axis and tick marks of the categorical axis.
  • offset: Please specify a vector indicating, How much the bars should shift relative to X-Axis
  • add: It is a Boolean argument, and by default, it is FALSE. If it is TRUE, bars added to an already existing plot.
  • legend: List of arguments you want to add to the legend() function.

Create a basic bar Chart in R

In this example, we show how to create a bar chart using the vectors in R programming

# Basic barplot in R Example

values <-  c(906, 264, 689, 739, 938)

barplot(values)
Barplot in R Programming 1

First, we declared a vector of random numbers

values <-  c(906, 264, 689, 739, 938)

Next, we used the R barplot function to draw the bar chart. From the below code snippet, you can observe that bar height decided on the values.

barplot(values)

Create a barplot in R using CSV

In this example, we create a Bar Chart in R using the external data or CSV. For this, we are importing data from the CSV file using the read.csv function. I suggest you refer R Read CSV article to understand the steps involved in CSV file import in R Programming.

# R Barplot Example
getwd()

employee <- read.csv("Products.csv", TRUE, sep = ",", 
                     na.strings = TRUE)
data <- aggregate(employee$SalesAmount, 
                  by=list(employee$Color), 
                  FUN=sum)
print(data)

barplot(data$x, main = "Sales By Product Color")
Barplot in R Programming 2

The following statement import the data from the CSV file

employee <- read.csv("Products.csv", TRUE, sep = ",", 
                     na.strings = TRUE)

From the below code snippet, see that we used the Aggregate function to find the total amount of sales of each color. Or we can say the Sum of Sales Amount Group By product Color.

data <- aggregate(employee$SalesAmount, 
                  by=list(employee$Color), 
                  FUN=sum)

The above statement returns the output as a List. So, we are using the $ to extract the aggregated data (sum of sales amount) from List.

barplot(data$x, main = "Sales By Product Color")

Assigning names to barplot in R Programming

In this example, we assign names to R bar chart, X-Axis, Y-Axis, and individual bars using main, xlab, ylab, and names

# R Barplot - Assign Names to X, Y Axis Example
getwd()

employee <- read.csv("Products.csv", TRUE, sep = ",", 
                     na.strings = TRUE)
output <- aggregate(employee$SalesAmount, 
                  by=list(employee$Color), 
                  FUN=sum)
print(output)

barplot(output$x, 
        main = "Sales By Product Color",
        xlab = "Product Colors",
        ylab = "Sales",
        names = output$Group.1)
Barplot in R Programming 3

Change Colors of barplot in R

In this example, we change the R bar chart colors using col argument, and border colors using border argument in R.

# R Barplot - Changing Colors of Bar and Borders Example
getwd()

employee <- read.csv("Products.csv", TRUE, sep = ",", 
                     na.strings = TRUE)
output <- aggregate(employee$SalesAmount, 
                  by=list(employee$Color), 
                  FUN=sum)
print(output)

barplot(output$x, 
        main = "Sales By Product Color",
        xlab = "Product Colors",
        ylab = "Sales",
        names = output$Group.1,
        col = "chocolate",
        border = "red")
Barplot in R Programming 4

TIP: To assign different border colors to use a Vector of colors. For example, border = c(“red”, “black”, “green”, …)

Horizontal Bar Chart in R Programming

In this example, we change the default vertical bar chart into a horizontal bar chart using horiz argument in R. We also change the bar density using density argument in R barplot

# R Barplot - Horizontal Bar Chart Example
getwd()

employee <- read.csv("Products.csv", TRUE, sep = ",", 
                     na.strings = TRUE)
output <- aggregate(employee$SalesAmount, 
                  by=list(employee$Color), 
                  FUN=sum)
print(output)

barplot(output$x, 
        main = "Sales By Product Color",
        xlab = "Product Colors",
        ylab = "Sales",
        names = output$Group.1,
        col = "chocolate",
        horiz = TRUE,
        density = 80,
        border = "red")
Barplot in R Programming 5

Create Stacked Barplot in R Programming

Let us see how to create a stacked barplot in R, and how to add Legend to the bar chart using the legend function

# R Stacked Barplot - Horizontal Bar Chart Example
getwd()

employee <- read.csv("Products.csv", TRUE, sep = ",", na.strings = TRUE)
count <- table(employee$SalesAmount, employee$Color)
count
cols = c("Black", "Blue", "brown", 
         "green", "Red", "gray", "White", "Yellow")
barplot(count, col = cols)

legend("topright", 
       c("Black", "Blue", "Multi", "No Color", 
         "Red", "Silver", "White", "Yellow"), 
       fill = cols )
Barplot in R Programming 6

The following statement creates a table with records of sales amount and color. Here, column values are unique colors, and row values are unique sales amount.

count <- table(employee$SalesAmount, employee$Color)

Next, we are creating a stacked bar chart in R using the above-specified table.

barplot(count, col = cols)

Create Juxtaposed Barplot in R Programming

In this example, we create a juxtaposed barplot in R programming language using beside argument

# R Juxtaposed Barplot Example
getwd()

employee <- read.csv("Products.csv", TRUE, sep = ","
                     , na.strings = TRUE)
count <- table(employee$SalesAmount, employee$Color)
count
cols = c("Black", "Blue", "brown", 
         "green", "Red", "gray", "White", "Yellow")
barplot(count, col = cols, beside = TRUE)

legend("topright", 
       c("Black", "Blue", "Multi", "No Color", 
         "Red", "Silver", "White", "Yellow"), 
       fill = cols )
Barplot in R Programming 7

Use Matrix to create Barplot in R Programming

In this example, we create a bar chart using Matrix values in R.

# Create R barplot using Matrix Example

vec <- c(4, 9, 11, 12, 17, 6, 9, 23, 2, 15, 1, 8 ) 
values <-  matrix(vec, nrow = 3, ncol = 4)
values
barplot(values, col = c("brown", "chocolate", "yellow"))
Barplot in R Programming 8

Comments are closed.