The Wayback Machine - https://web.archive.org/web/20240911040623/https://www.geeksforgeeks.org/r-bar-charts/
Open In App

R – Bar Charts

Last Updated : 29 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Bar charts are a popular and effective way to visually represent categorical data in a structured manner. R stands out as a powerful programming language for data analysis and visualization. In this article, we’ll look at how to make visually appealing bar charts in R.

Bar Charts using R

A bar chart also known as bar graph is a pictorial representation of data that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. In other words, it is the pictorial representation of the dataset. These data sets contain the numerical values of variables that represent the length or height.

R uses the barplot() function to create bar charts. Here, both vertical and Horizontal bars can be drawn.

Syntax:

barplot(H, xlab, ylab, main, names.arg, col)

Parameters:

  • H: This parameter is a vector or matrix containing numeric values which are used in bar chart.
  • xlab: This parameter is the label for x axis in bar chart.
  • ylab: This parameter is the label for y axis in bar chart.
  • main: This parameter is the title of the bar chart.
  • names.arg: This parameter is a vector of names appearing under each bar in bar chart.
  • col: This parameter is used to give colors to the bars in the graph.

Creating a Simple Bar Chart in R

In order to create a Bar Chart:

  1. A vector (H <- c(Values…)) is taken which contains numeral values to be used.
  2. This vector H is plot using barplot().

R




# Create the data for the chart
A <- c(17, 32, 8, 53, 1)
 
# Plot the bar chart
barplot(A, xlab = "X-axis", ylab = "Y-axis", main ="Bar-Chart")


Output:

Bar Chart-Geeksforgeeks

R – Bar Charts

Creating a Horizontal Bar Chart in R

To create a horizontal bar chart:

  1. Take all parameters which are required to make a simple bar chart.
  2. Now to make it horizontal new parameter is added.
    barplot(A, horiz=TRUE )

Creating a horizontal bar chart

R




# Create the data for the chart
A <- c(17, 32, 8, 53, 1)
 
# Plot the bar chart
barplot(A, horiz = TRUE, xlab = "X-axis",
        ylab = "Y-axis", main ="Horizontal Bar Chart"
       )


Output:

Horizontal Bar Chart-Geeksforgeeks

Horizontal Bar Chart

Adding Label, Title and Color in the BarChart

Label, title and colors are some properties in the bar chart which can be added to the bar by adding and passing an argument.

  1. To add the title in bar chart.
    barplot( A, main = title_name )
  2. X-axis and Y-axis can be labeled in bar chart. To add the label in bar chart.
    barplot( A, xlab= x_label_name, ylab= y_label_name)
  3. To add the color in bar chart.
    barplot( A, col=color_name)

Implementations

R




# Create the data for the chart
A <- c(17, 2, 8, 13, 1, 22)
B <- c("Jan", "feb", "Mar", "Apr", "May", "Jun")
 
# Plot the bar chart
barplot(A, names.arg = B, xlab ="Month",
        ylab ="Articles", col ="green",
        main ="GeeksforGeeks-Article chart")


Output:

GeeksforGeeks-Article chart-Geeksforgeeks

R – GeeksforGeeks-Article chart

Add Data Values on the Bar

R




# Create the data for the chart
A <- c(17, 2, 8, 13, 1, 22)
B <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun")
 
# Plot the bar chart with text features
barplot(A, names.arg = B, xlab = "Month",
        ylab = "Articles", col = "steelblue",
        main = "GeeksforGeeks - Article Chart",
        cex.main = 1.5, cex.lab = 1.2, cex.axis = 1.1)
 
# Add data labels on top of each bar
text(
  x = barplot(A, names.arg = B, col = "steelblue", ylim = c(0, max(A) * 1.2)),
  y = A + 1, labels = A, pos = 3, cex = 1.2, col = "black"
)


Output:

GeeksforGeeks - Article Chart-Geeksforgeeks

GeeksforGeeks – Article Chart

  • cex.main, cex.lab, and cex.axis: These arguments control the font size of the chart title, x-axis label, and y-axis label, respectively. They are set to 1.5, 1.2, and 1.1 to increase the font size for better readability.
  • text(): We use the text() function to add data labels on top of each bar. The x argument specifies the x-coordinates of the labels (same as the barplot() x-coordinates), the y argument adds a value of 1 to the corresponding bar heights (A + 1) to position the labels just above the bars.

Creating Stacked and Grouped Bar Chart in R

The bar chart can be represented in two form group of bars and stacked.

  1. Take a vector value and make it matrix M which to be grouped or stacked. Making of matrix can be done by.
    M <- matrix(c(values...), nrow = no_of_rows, ncol = no_of_column, byrow = TRUE)
  2. To display the bar explicitly we can use the beside parameter.
    barplot( beside=TRUE )

Grouped Bar Chart:

R




colors = c("green", "orange", "brown")
months <- c("Mar", "Apr", "May", "Jun", "Jul")
regions <- c("East", "West", "North")
 
# Create the matrix of the values.
Values <- matrix(c(2, 9, 3, 11, 9, 4, 8, 7, 3, 12, 5, 2, 8, 10, 11),
                nrow = 3, ncol = 5, byrow = TRUE)
 
# Create the bar chart
barplot(Values, main = "Total Revenue", names.arg = months,
                        xlab = "Month", ylab = "Revenue",
                        col = colors, beside = TRUE)
 
# Add the legend to the chart
legend("topleft", regions, cex = 0.7, fill = colors)


Output:

R - Total Revenue -Geeksforgeeks

R – Total Revenue

Stacked Bar Chart:

R




colors = c("green", "orange", "brown")
months <- c("Mar", "Apr", "May", "Jun", "Jul")
regions <- c("East", "West", "North")
 
# Create the matrix of the values.
Values <- matrix(c(2, 9, 3, 11, 9, 4, 8, 7, 3, 12, 5, 2, 8, 10, 11),
                nrow = 3, ncol = 5, byrow = TRUE)
 
# Create the bar chart
barplot(Values, main = "Total Revenue", names.arg = months,
        xlab = "Month", ylab = "Revenue", col = colors)
 
# Add the legend to the chart
legend("topleft", regions, cex = 0.7, fill = colors)


Output:

ing

R – Bar Charts



Previous Article
Next Article

Similar Reads

Side by Side bar charts in R
In this article, we will discuss how to draw Bar Charts side by side in R Programming Language. Method 1: Using par() function To draw plots side by side par() function is used. Syntax: par(mfrow, mar, mgp, las) Parameters: mfrow- A numeric vector of length 2, which sets the rows and column in which frame has to be divided.mar – A numeric vector of
2 min read
How to Make Grouped Bar Plot with Same Bar Width in R
In this article, we will discuss How to Make Grouped Bar Plot with the Same Bar Width in R Programming Language. Method 1 : Using position_dodge2(preserve = “single”) The geom_col() method can be used to add positions to the graph. Dodging preserves the vertical position of an geom while adjusting the horizontal position. The position_dodge2 method
2 min read
Create Multiple Pie Charts using ggplot2 in R
Pie Chart, also known as circle chart, is the graphical representation of the relative size or frequency of the data in a circular format. Basically, it helps in visualizing the relative size or frequency of a particular group of data as a part of the whole. This article discusses how multiple pie charts can be created into one frame for consecutiv
3 min read
R - Charts and Graphs
R language is mostly used for statistics and data analytics purposes to represent the data graphically in the software. To represent those data graphically, charts and graphs are used in R. R - graphs There are hundreds of charts and graphs present in R. For example, bar plot, box plot, mosaic plot, dot chart, coplot, histogram, pie chart, scatter
6 min read
Adding Colors to Charts in R Programming
R Programming language is mostly used for statistics and data analytics purposes to represent the data graphically in the software. To represent those data graphically, charts and graphs are used in R. Adding Colors to Charts in R Programming There are hundreds of charts and graphs present in R. For example, bar plot, box plot, mosaic plot, dot cha
4 min read
Create Dot Charts in R Programming - dotchart () Function
dotchart() function in R Language is used to create a dot chart of the specified data. A dot chart is defined as a plot which is used to draw a Cleveland dot plot. Syntax: dotchart(x, labels = NULL, groups = NULL, gcolor = par("fg"), color = par("fg")) Parameters: x: it is defined as numeric vector or matrix labels: a vector of labels for each poin
2 min read
Interactive Charts using Pywedge package
In Machine Learning and Data Science, one of the toughest jobs is to understand the raw data and make it fit for applying different models over it to make predictions. For understanding purpose, we make use of different processes like checking statistical figures such as mean, median, mode, finding the relation between features, looking at the dist
4 min read
Pie Charts in R using ggplot2
A Pie Chart or Circle Chart is a circular statistical graphical technique that divides the circle in numeric proportion to represent data as a part of the whole. In Circle Chart the arc length of each slice is proportional to the quantity it represents. Pie charts are very widely used in the business world and the mass media to understand trends. A
2 min read
Side by Side pie charts in R
In this article, we will discuss how to draw Pie Charts side by side in R Programming Language. Method 1: Using base R functions To draw plots side by side par() function is used. Syntax: par(mfrow, mar, mgp, las) Parameters: mfrow- A numeric vector of length 2, which sets the rows and column in which frame has to be divided.mar – A numeric vector
2 min read
Side by Side Scatter charts in R
In this article, we will discuss how to make side by side scatter plot in R Programming Language. Method 1: Using par() function Here we will use par() function to divide frames into grids. Syntax: par(mfrow, mar, mgp, las) Parameters: mfrow: A numeric vector of length 2, which sets the rows and column in which frame has to be divided.mar: A numeri
2 min read
Side by Side Line charts in R
In this article, we will discuss how to make side by side line chart in R Programming Language. Method 1: Using par() function Here we will use par() function to divide frames into grids. Syntax: par(mfrow, mar, mgp, las) Parameters: mfrow: A numeric vector of length 2, which sets the rows and column in which frame has to be divided.mar: A numeric
2 min read
How to Create Radar Charts in R?
In this article, we are going to see how to create Radar Charts in R Programming Language. Radar charts are also known as Spider or Web or Polar charts. It is a graphical graph to display multivariate data in form of 2D charts of three or more quantitative variables which are represented on axes starting from the same point Dataset in use: Mumbai T
3 min read
How to embed ggvis interactive charts in RMarkdown
The ggvis is an R package that provides a system for creating the interactive data visualizations. RMarkdown is a tool for creating dynamic documents that combine code, text, and output. To embed ggvis interactive charts in RMarkdown, use the ggvisOutput and renderGgvis functions from the ggvis package. RMarkdown RMarkdown is a file format that all
4 min read
How to build Animated Charts like Hans Rosling
Animated charts in R or Animated plots are dynamic visualizations that show changes in data over specified variables like time and others. They allow us to present data in a more engaging and interactive manner like an animation or a GIF, revealing patterns and relationships that might be difficult to observe in static plots. To create animated cha
14 min read
Polar Charts in R
Polar charts, sometimes referred to as radial charts or spider charts, are effective tools for data visualization that show data points in a circular, two-dimensional layout. In R Programming Language These graphs are very helpful for showing multivariate data, highlighting patterns, and comparing various variables across various categories or data
7 min read
Star Charts in Python
Star plot or Radar Chart is used for displaying multivariate data, in which each variable provides the measure of some common property of each observation. Each star in the plot represents a single observation. Star plot is used to examine the relative values of a single data point and locate similar and dissimilar points. The star plot consists of
3 min read
Interactive Charts using Plotly in R
R Programming Language is a powerful tool for data analysis and visualization. Interactive plots with R can be particularly useful for exploring and presenting data, but creating them can be challenging. The Shiny package provides a framework for creating web-based applications with R, including interactive plots. However, Shiny can be complex and
5 min read
R - Pie Charts
A pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. It depicts a special chart that uses "pie slices", where each sector shows the relative sizes of data. A circular chart cuts in the form of radii into segments describing relative frequencies or magnitude also known as a circle graph.  R
4 min read
Basic Python Charts
Python Chart is part of data visualization to present data in a graphical format. It helps people understand the significance of data by summarizing and presenting huge amounts of data in a simple and easy-to-understand format and helps communicate information clearly and effectively. In this article, we will be discussing various Python Charts tha
6 min read
Creating Charts using openpyxl
Charts are a powerful way to visualize data, making it easier to analyze and present information. While working with Excel files in Python, the library openpyxl comes into the picture and can be used as a tool for automating tasks like reading data, writing data, formatting cells, and of course creating charts. In this article, we will learn to cre
7 min read
How to customize the axis of a Bar Plot in R
Barplots in R programming language can be created using the barplot() method. It takes as input a matrix or vector of values. The bar heights are equivalent to the values contained in the vector. Syntax: barplot(H, xlab, ylab, main, names.arg, col) Labeling the X-axis of the bar plot The names.args attribute in the barplot() method can be used to a
4 min read
Set Aspect Ratio of Scatter Plot and Bar Plot in R Programming - Using asp in plot() Function
asp is a parameter of the plot() function in R Language is used to set aspect ratio of plots (Scatterplot and Barplot). Aspect ratio is defined as proportional relationship between width and height of the plot axes. Syntax: plot(x, y, asp ) Parameters: x, y: Coordinates of x and y axis asp: Aspect ratio Example 1: # Set seed for reproducibility set
1 min read
Change the error bar thickness in Matplotlib
Matplotlib is a Python library which is widely used by data analytics. Matplotlib.pyplot.errorbar() is a pyplot module consisting of a function which provides a MATLAB like interface. Changing Error Bar Thickness Before changing the thickness of error bar let us see what error bar is and how we can plot and use them. Error Bar: Error bars are bars
2 min read
Stacked Bar Chart in R
A stacked bar chart extends the standard bar chart from looking at numeric values across one categorical variable to two. Each bar in a standard bar chart is divided into a number of sub-bars stacked end to end, each one corresponding to a level of the second categorical variable. This article discusses how one can be created using R. The function
2 min read
Showing data values on stacked bar chart in ggplot2 in R
In this article, you'll learn how to show data values on a stacked bar chart in ggplot2 in R Programming Language. To show the data into the Stacked bar chart you have to use another parameter called geom_text(). Syntax: geom_text(size, position = position_stack(vjust = value), colour) Here the size represents the size of the font that will appear
2 min read
How to change the order of bars in bar chart in R ?
In this article, we will discuss how to change the order of bars in bar chart in R programming language. We can change the order of bars by using two plots ggplot and barplot. Method 1: Ggplot re-ordering Firstly create a sample dataset and plot the graph-Manual. Now let's reorder them accordingly. Dataset in Use: Reordering in ggplot is done using
4 min read
Combine bar and line chart in ggplot2 in R
Sometimes while dealing with hierarchical data we need to combine two or more various chart types into a single chart for better visualization and analysis. These are known as “Combination charts”. In this article, we are going to see how to combine a bar chart and a line chart in R Programming Language using ggplot2. Dataset in use: Courses Sold v
4 min read
How to add percentage or count labels above percentage bar plot in R?
In this article, we will discuss how to add percentage or count above percentage bar plot in R programming language. The ggplot() method of this package is used to initialize a ggplot object. It can be used to declare the input data frame for a graphic and can also be used to specify the set of plot aesthetics. The ggplot() function is used to cons
3 min read
How to Highlight a Bar in Barplot in R?
In this article, we will discuss how to highlight a bar in barplot in R Programming language. First, let's create a basic barplot with no bars highlighted using ggplot2. C/C++ Code # Create sample data set.seed(5642) sample_data &lt;- data.frame(name = c(&quot;Geek1&quot;,&quot;Geek2&quot;, &quot;Geek3&quot;,&quot;Geek4&quot;, &quot;Geeek5&quot;) ,
2 min read
How to Add Labels Over Each Bar in Barplot in R?
In this article, we will see how to add labels over each bar in barplot in R Programming language. To add labels on top of each bar in Barplot in R we use the geom_text() function of the ggplot2 package. Syntax: plot+ geom_text(aes(label = value, nudge_y ) Parameters: value: value field of which labels have to display.nudge_y: distance shift in the
2 min read
Practice Tags :