The Wayback Machine - https://web.archive.org/web/20240927030344/https://www.geeksforgeeks.org/data-visualization-with-r-and-ggplot2/
Open In App

Data visualization with R and ggplot2

Last Updated : 20 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Data visualization with R and ggplot2 in R Programming Language also termed as Grammar of Graphics is a free, open-source, and easy-to-use visualization package widely used in R Programming Language. It is the most powerful visualization package written by Hadley Wickham.

It includes several layers on which it is governed. The layers are as follows:

Building Blocks of layers with the grammar of graphics

  • Data: The element is the data set itself
  • Aesthetics: The data is to map onto the Aesthetics attributes such as x-axis, y-axis, color, fill, size, labels, alpha, shape, line width, line type
  • Geometrics: How our data being displayed using point, line, histogram, bar, boxplot
  • Facets: It displays the subset of the data using Columns and rows
  • Statistics: Binning, smoothing, descriptive, intermediate
  • Coordinates: the space between data and display using Cartesian, fixed, polar, limits
  • Themes: Non-data link

Dataset Used

mtcars(motor trend car road test) comprise fuel consumption and 10 aspects of automobile design and performance for 32 automobiles and come pre-installed with dplyr package in R.

R




# Print the top 5 records of the dataset
head(mtcars)


Output:

                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

Now we load dplyr library and print the summary of mtcars dataset using summary function.

R




# Installing the package
install.packages("dplyr")
 
# Loading package
library(dplyr)
 
# Summary of dataset in package
summary(mtcars)


Output:

      mpg             cyl             disp             hp       
Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0
1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5
Median :19.20 Median :6.000 Median :196.3 Median :123.0
Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7
3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0
Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0
drat wt qsec vs
Min. :2.760 Min. :1.513 Min. :14.50 Min. :0.0000
1st Qu.:3.080 1st Qu.:2.581 1st Qu.:16.89 1st Qu.:0.0000
Median :3.695 Median :3.325 Median :17.71 Median :0.0000
Mean :3.597 Mean :3.217 Mean :17.85 Mean :0.4375
3rd Qu.:3.920 3rd Qu.:3.610 3rd Qu.:18.90 3rd Qu.:1.0000
Max. :4.930 Max. :5.424 Max. :22.90 Max. :1.0000
am gear carb
Min. :0.0000 Min. :3.000 Min. :1.000
1st Qu.:0.0000 1st Qu.:3.000 1st Qu.:2.000
Median :0.0000 Median :4.000 Median :2.000
Mean :0.4062 Mean :3.688 Mean :2.812
3rd Qu.:1.0000 3rd Qu.:4.000 3rd Qu.:4.000
Max. :1.0000 Max. :5.000 Max. :8.000

ggplot2 in R

We devise visualizations on mtcars dataset which includes 32 car brands and 11 attributes using ggplot2 layers.

Data Layer:

ggplot2 in R the data Layer we define the source of the information to be visualize, let’s use the mtcars dataset in the ggplot2 package.

R




library(ggplot2)
library(dplyr)
 
ggplot(data = mtcars) +
  labs(title = "MTCars Data Plot")


Output:

Data visualization with R and ggplot2

ggplot2 in R

Aesthetic Layer:

ggplot2 in R Here we will display and map dataset into certain aesthetics.

R




# Aesthetic Layer
ggplot(data = mtcars, aes(x = hp, y = mpg, col = disp))+
 labs(title = "MTCars Data Plot")


Output:

Data visualization with R and ggplot2

ggplot2 in R

Geometric layer:

ggplot2 in R geometric layer control the essential elements, see how our data being displayed using point, line, histogram, bar, boxplot.

R




# Geometric layer
ggplot(data = mtcars, aes(x = hp, y = mpg, col = disp)) +
  geom_point() +
  labs(title = "Miles per Gallon vs Horsepower",
       x = "Horsepower",
       y = "Miles per Gallon")


Output:

Data visualization with R and ggplot2

Data visualization with R and ggplot2

Geometric layer: Adding Size, color, and shape and then plotting the Histogram plot

R




# Adding size
ggplot(data = mtcars, aes(x = hp, y = mpg, size = disp)) +
  geom_point() +
  labs(title = "Miles per Gallon vs Horsepower",
       x = "Horsepower",
       y = "Miles per Gallon")
 
# Adding shape and color
ggplot(data = mtcars, aes(x = hp, y = mpg, col = factor(cyl),
       shape = factor(am))) +geom_point() +
  labs(title = "Miles per Gallon vs Horsepower",
       x = "Horsepower",
       y = "Miles per Gallon")
 
# Histogram plot
ggplot(data = mtcars, aes(x = hp)) +
  geom_histogram(binwidth = 5) +
  labs(title = "Histogram of Horsepower",
       x = "Horsepower",
       y = "Count")


Output:

Data visualization with R and ggplot2

Data visualization with R and ggplot2

Data visualization with R and ggplot2

Data visualization with R and ggplot2

Data visualization with R and ggplot2

Data visualization with R and ggplot2

Facet Layer:

ggplot2 in R facet layer is used to split the data up into subsets of the entire dataset and it allows the subsets to be visualized on the same plot. Here we separate rows according to transmission type and Separate columns according to cylinders.

R




# Facet Layer
# Separate rows according to transmission type
p <- ggplot(data = mtcars, aes(x = hp, y = mpg, shape = factor(cyl))) + geom_point()
 
p + facet_grid(am ~ .) +
  labs(title = "Miles per Gallon vs Horsepower",
       x = "Horsepower",
       y = "Miles per Gallon")
 
# Separate columns according to cylinders
p <- ggplot(data = mtcars, aes(x = hp, y = mpg, shape = factor(cyl))) + geom_point()
 
p + facet_grid(. ~ cyl) +
  labs(title = "Miles per Gallon vs Horsepower",
       x = "Horsepower",
       y = "Miles per Gallon")


Output:

Data visualization with R and ggplot2

Data visualization with R and ggplot2Data visualization with R and ggplot2

Data visualization with R and ggplot2

Data visualization with R and ggplot2

Statistics layer

ggplot2 in R this layer, we transform our data using binning, smoothing, descriptive, intermediate

R




ggplot(data = mtcars, aes(x = hp, y = mpg)) +
  geom_point() +
  stat_smooth(method = lm, col = "red") +
  labs(title = "Miles per Gallon vs Horsepower")


Output:

Data visualization with R and ggplot2

Data visualization with R and ggplot2

Coordinates layer:

ggplot2 in R these layers, data coordinates are mapped together to the mentioned plane of the graphic and we adjust the axis and changes the spacing of displayed data with Control plot dimensions.

R




ggplot(data = mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  stat_smooth(method = lm, col = "red") +
  scale_y_continuous("Miles per Gallon", limits = c(2, 35), expand = c(0, 0)) +
  scale_x_continuous("Weight", limits = c(0, 25), expand = c(0, 0)) +
  coord_equal() +
  labs(title = "Miles per Gallon vs Weight",
       x = "Weight",
       y = "Miles per Gallon")


Output:

Data visualization with R and ggplot2

Data visualization with R and ggplot2

Coord_cartesian() to proper zoom in:

R




# Add coord_cartesian() to proper zoom in
ggplot(data = mtcars, aes(x = wt, y = hp, col = am)) +
                        geom_point() + geom_smooth() +
                        coord_cartesian(xlim = c(3, 6))


Output:

Data visualization with R and ggplot2

Data visualization with R and ggplot2

Theme Layer:

ggplot2 in R layer controls the finer points of display like the font size and background color properties.

Example 1: Theme layer – element_rect() function

R




ggplot(data = mtcars, aes(x = hp, y = mpg)) +
  geom_point() +
  facet_grid(. ~ cyl) +
  theme(plot.background = element_rect(fill = "blue", colour = "gray")) +
  labs(title = "Miles per Gallon vs Horsepower")


Output:

Data visualization with R and ggplot2

Data visualization with R and ggplot2

Example 2:

R




ggplot(data = mtcars, aes(x = hp, y = mpg)) +
        geom_point() + facet_grid(am ~ cyl) +
        theme_gray()+
 labs(title = "Miles per Gallon vs Horsepower")


Output:

Data visualization with R and ggplot2

Data visualization with R and ggplot2

ggplot2 in R provides various types of visualizations. More parameters can be used included in the package as the package gives greater control over the visualizations of data. Many packages can integrate with the ggplot2 package to make the visualizations interactive and animated.

Contour plot for the mtcars dataset

R




# Install and load required packages
install.packages("ggplot2")
library(ggplot2)
 
# Create a 2D density contour plot for the mtcars dataset
ggplot(mtcars, aes(x = wt, y = mpg)) +
  stat_density_2d(aes(fill = ..level..), geom = "polygon", color = "white") +
  scale_fill_viridis_c() +
  labs(title = "2D Density Contour Plot of mtcars Dataset",
       x = "Weight (wt)",
       y = "Miles per Gallon (mpg)",
       fill = "Density") +
  theme_minimal()


Output:

gh

Data visualization with R and ggplot2

In ggplot2 in R stat_density_2d to generate the 2D density contour plot. The aesthetics x and y specify the variables on the x-axis and y-axis, respectively. The fill aesthetic is set to ..level.. to map fill color to density levels.

Creating a panel of different plots

R




library(ggplot2)
library(gridExtra)
 
# Selecting specific columns from mtcars dataset
selected_cols <- c("mpg", "disp", "hp", "drat")
selected_data <- mtcars[, selected_cols]
 
# Create histograms for individual variables
hist_plot_mpg <- ggplot(selected_data, aes(x = mpg)) +
  geom_histogram(binwidth = 2, fill = "blue", color = "white") +
  labs(title = "Histogram: Miles per Gallon", x = "Miles per Gallon", y = "Frequency")
 
hist_plot_disp <- ggplot(selected_data, aes(x = disp)) +
  geom_histogram(binwidth = 50, fill = "red", color = "white") +
  labs(title = "Histogram: Displacement", x = "Displacement", y = "Frequency")
 
hist_plot_hp <- ggplot(selected_data, aes(x = hp)) +
  geom_histogram(binwidth = 20, fill = "green", color = "white") +
  labs(title = "Histogram: Horsepower", x = "Horsepower", y = "Frequency")
 
hist_plot_drat <- ggplot(selected_data, aes(x = drat)) +
  geom_histogram(binwidth = 0.5, fill = "orange", color = "white") +
  labs(title = "Histogram: Drat", x = "Drat", y = "Frequency")
 
# Arrange the plots in a grid
grid.arrange(hist_plot_mpg, hist_plot_disp, hist_plot_hp, hist_plot_drat,
             ncol = 2)


Output:

gh

Data visualization with R and ggplot2

The ggplot2 and gridExtra packages to create histograms for four different variables (“Miles per Gallon,” “Displacement,” “Horsepower,” and “Drat”) from the mtcars dataset.

Each histogram is visually represented in a distinctive color (blue, red, green, and orange) with white borders. The resulting grid of histograms provides a quick visual overview of the distribution of these car-related variables.

Save and extract R plots:

To save and extract plots in R, you can use the ggsave function from the ggplot2 package. Here’s an example of how to save and extract plots:

R




# Create a plot
plot <- ggplot(data = mtcars, aes(x = hp, y = mpg)) +
  geom_point() +
  labs(title = "Miles per Gallon vs Horsepower")
 
# Save the plot as an image file (e.g., PNG)
ggsave("plot.png", plot)
 
# Save the plot as a PDF file
ggsave("plot.pdf", plot)
 
# Extract the plot as a variable for further use
extracted_plot <- plot
plot


Output:

Data visualization with R and ggplot2

Data visualization with R and ggplot2

In this demonstration, I used ggplot to construct a plot and the ggsave function to save it as a PDF file (plot.pdf) and a PNG image file (plot.png). By including the correct file extension, you can indicate the intended file format.

You may easily give the ggplot object to a variable, as demonstrated with extracted_plot, to extract the plot as a variable for later usage.

Be sure to substitute your unique plot and desired file names for the plot code and file names (plot.png and plot.pdf).



Previous Article
Next Article

Similar Reads

Master Data Visualization With ggplot2
In this article, we are going to see the master data visualization with ggplot2 in R Programming Language. Generally, data visualization is the pictorial representation of a dataset in a visual format like charts, plots, etc. These are the important graphs in data visualization with ggplot2, Bar ChartViolin PlotsDensity PlotsBox PlotsPie ChartStack
8 min read
How to Save Time with Data Visualization using Stack in R with ggplot2
The widely used R package ggplot2 is used to produce beautiful and efficient data visualisations. Here are some pointers for speeding up data visualisation using the "stack" feature of ggplot2: Select the pertinent information: Make sure the data you plan to use in your visualisation is appropriate. You will need data that contains information on e
6 min read
Set Axis Limits of ggplot2 Facet Plot in R - ggplot2
In this article, we will discuss how to set the axis limits of the ggplot2 facet plot in the R programming language. Method 1: Set axis limits of ggplot2 facet plot with Free Scales Here the role of the ggplot2 package is to plot the facet plot and provide some functionalities to the user, further the user needs to set the argument of the scales fu
5 min read
Visualization of a correlation matrix using ggplot2 in R
In this article, we will discuss how to visualize a correlation matrix using ggplot2 package in R programming language. In order to do this, we will install a package called ggcorrplot package. With the help of this package, we can easily visualize a correlation matrix. We can also compute a matrix of correlation p-values by using a function that i
7 min read
Time series visualization with ggplot2 in R
In this article, we will discuss time-series visualization with the ggplot2 package in the R programming Language. A time series is the series of data points listed in the order timeline i.e. one of the axes in the form of dates, years, or months. A time series is a sequence of successive equal interval points in time. A time-series analysis consis
3 min read
Stock Data Analysis and Data Visualization with Quantmod in R
Analysis of historical stock price and volume data is done in order to obtain knowledge, make wise decisions, and create trading or investment strategies. The following elements are frequently included in the examination of stock data in the R Programming Language. Historical Price Data: Historical price data contains information about a stock's op
8 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
Data Visualisation using ggplot2(Scatter Plots)
The correlation Scatter Plot is a crucial tool in data visualization and helps to identify the relationship between two continuous variables. In this article, we will discuss how to create a Correlation Scatter Plot using ggplot2 in R. The ggplot2 library is a popular library used for creating beautiful and informative data visualizations in R Prog
7 min read
Zoom into ggplot2 Plot without Removing Data in R
In this article, we will discuss how to zoom into the ggplot2 plot without removing data using ggplot2 package in the R programming language. The approaches to the zoom into ggplot2 plot without removing data are as follows: Zoom in to ggplot2 plot without Removing data using ylim()/xlim() functionZoom in to ggplot2 plot without Removing data using
2 min read
How to Make Grouped Boxplot with Jittered Data Points in ggplot2 in R
In this article, we will see how to make use of ggplot2 package in R Programming Language to plot grouped boxplots with jittered data points. Grouped Boxplots help us visualize two or more features/variables in a single plot using the grouping variable in ggplot2. The jittered points are data points that belong to another variable and are plotted o
3 min read
Scale ggplot2 Color Gradient to Range Outside of Data in R
In this article, we are going to see how to Scale ggplot2 Color Gradient to Range Outside of Data in R Programming Language. Creating dataframe: Under this, we are simply creating a data frame of 6 rows and 3 columns. C/C++ Code df <- data.frame(x = seq(- 2, 2, 1), y = rep(seq(- 2, 2, 1), each = 5), z = round(rnorm(25, 50, 70))) head(df) Output:
2 min read
Smooth data for a geom_area graph Using ggplot2 in R
The ggplot2 package is a powerful and widely used package for graphic visualization. It can be used to provide a lot of aesthetic mappings to the plotted graphs. This package is widely available in R. The package can be downloaded and installed into the working space using the following command : install.packages("ggplot2") The ggplot method can be
3 min read
Data Visualization using GoogleVis Package
GoogleVis is a package in R that is used to act as an interface between R and the Google API to produce interactive charts which can be easily embedded into web pages. This package helps the user to plot the data without uploading them into google. In this article let's parse through some charts that can be plotted using googleVis in R Programming
5 min read
Data Visualization using ggvis Package in R
The ggvis is an interactive visualization package in R language that is based on the popular ggplot2 package. It allows you to create interactive plots and graphics that can be explored and manipulated by the user. ggvis supports a wide range of plot types including scatter plots, line charts, bar charts, histograms, and more. One of the key featur
15+ min read
Multivariate Data Visualization with R
A method for visualizing data with numerous variables is called multivariate data visualization with R. In this method, graphs and charts are made to show how the various factors relate to one another. The programming language R, which is frequently used for data visualization, provides a number of tools for the visualization of multivariate data.
5 min read
Data Visualization with Highcharter in R
Highcharter is an R package that provides an interface to Highcharts, a popular JavaScript charting library. Highcharts is built on top of jQuery and provides a wide range of chart types, including line charts, bar charts, scatter plots, and more. It is highly customizable and supports a wide range of options for styling and interactivity. In R Pro
7 min read
Top R Libraries for Data Visualization in 2024
When you are talking about data analysis, don’t forget data visualization! It is a very important part of data analysis that can reveal hidden trends and provide more insight into the data. Data visualization can provide information just by looking at them whereas it would take much more time to obtain that same information from spreadsheets or tex
7 min read
How Good is R for Data Visualization?
R is highly regarded for data visualization due to its robust set of libraries and packages designed specifically for this purpose due to the following reasons: Comprehensive Visualization Packages:ggplot2: Based on the grammar of graphics, ggplot2 allows users to build complex and multi-layered visualizations with a high degree of customization. I
2 min read
Getting started with Data Visualization in R
Data visualization is the technique used to deliver insights in data using visual cues such as graphs, charts, maps, and many others. This is useful as it helps in intuitive and easy understanding of the large quantities of data and thereby make better decisions regarding it. Data Visualization in R Programming LanguageThe popular data visualizatio
6 min read
Interactive Data Visualization with Plotly Express in R
Data Visualization in R is the process of representing data so that it is easy to understand and interpret. Various packages are present in the R Programming Language for data visualization. Plotly's R graphing library makes interactive, publication-quality graphs. Plotly can be used to make various interactive graphs such as scatter, line, bar, hi
9 min read
Combine and Modify ggplot2 Legends with Ribbons and Lines
The ggplot2 library is often used for data visualization. One feature of ggplot2 is the ability to create and modify legends for plots. In this tutorial, we will cover how to combine and modify ggplot2 legends with ribbons and lines. To begin, make sure you have the ggplot2 library installed and loaded in your R Stusio. Concepts related to the topi
4 min read
ggplot2 - Title and Subtitle with Different Size and Color in R
A Title and the subtitle to a plot give a piece of information about the graph that what the graph actually wants to represent. This article describes how to add a Title and Subtitle with Different Sizes and Colors using ggplot2 in R Programming. To add a Title and Subtitle within a plot, first, we have to import ggplot2 library using library() fun
5 min read
Control Line Color and Type in ggplot2 Plot Legend in R
In this article, we will see how to control line color and type in ggplot2 plot legend in the R programming language. Using Default Parameters In this method, inbuilt attributes are passed to the function with appropriate values to generate the requirement. Thus, in order to change the color, col or color attribute has to be passed with the column
2 min read
Remove grid and background from plot using ggplot2 in R
Prerequisite: ggplot2 in R programming A plot by default is produced with a grid background and grayish colored background. This article discusses how they can be removed. The examples given below use line plot, but the same can be employed for any other Visualization. Approach Create data framePlot normallyNow add functions to make changesDisplay
2 min read
Grouped, stacked and percent stacked barplot in ggplot2
The ggplot is a library used for generating graphs in R language. We provide the data and specify the aesthetics as to how the specified data should be mapped. It is a very powerful library and widely used to generate comprehensive graphs and plots. It is used for creating graphics based on the "Grammar of Graphics". A Bar Plot or Bar Chart is a Da
5 min read
Add Bold and Italic text to ggplot2 Plot in R
In this article, we will discuss how to add Bold and Italic Text to a plot using ggplot2 in the R Programming language. To add the bold and italic text we will be using the annotate() function from the ggplot2 library in R language, this function helps to add the text to the graph with different variations in the ggplot2 plot. Install the ggplot2 l
3 min read
How to adjust Space Between ggplot2 Axis Labels and Plot Area in R ?
While plotting the graphs we can make different changes in order to make them much more appealing and clear to the observer. One of the ways is to adjust the spacing between the labels and plot area. In this article, we will study how to adjust space between ggplot2 Axis Labels and plot area in R Programming Language. To add customizations to our p
1 min read
Add Vertical and Horizontal Lines to ggplot2 Plot in R
In this article, we will see how to add Vertical and Horizontal lines to the plot using ggplot2 in R Programming Language. Adding Vertical Line To R Plot using geom_vline() For adding the Vertical line to the R plot, geom_vline() draws a vertical line at a specified position. Syntax: geom_vline(xintercept) Parameter: here xintercept is used control
3 min read
Change Space and Width of Bars in ggplot2 Barplot in R
In this article, we will see how to change the Space and width of bars in ggplot2 barplot in R. For Create a simple Barplot using ggplot2, first we have to load the ggplot2 package using the library() function. If you have not already installed then you can install it by writing the below command in your R Console. install.packages("ggplot2") Then
4 min read
Changing Font Size and Direction of Axes Text in ggplot2 in R
In this article, we will discuss how to change the font size and the direction of the axis text using the ggplot2 plot in R Programming language. For both of the requirement theme() function is employed. After plotting a regular graph, simply adding theme() with appropriate values will get the job done. theme() function: Use of this function is a p
2 min read