Tutorial for Histogram in R using ggplot2 with Examples

In this tutorial, we will explain how to create histogram in R with ggplot2 package which is a very popular open-source package in R for creating visualizations. First of all, we will understand the syntax of geom_histogram() which is the ggplot2 geometric object for creating histograms. Then we will see multiple examples of creating histograms in ggplot2.

Syntax of Scatter Plot in ggplot2

The minimal syntax for creating the scatter plot in ggplot2 is

ggplot(<data>, mapping = aes(<mapping>) + geom_histogram()

ggplot2 lets you add more layers to the plot such as theme, labs, etc. to create more advanced histograms.

Loading Library and Dataset

Let us start by loading the ggplot2 library.

We are going to use the stroke dataset for all ggplot2 histogram examples. We load this data into a data frame and check the top rows using the head command.

Out[0]:

Example 2: Horizontal Histogram in ggplot2

We can create a horizontal histogram in ggplot2 by using the coord_flip() that can flip a vertical histogram into a horizontal histogram.
Out[3]:
Out[7]:
Out[9]:
Out[10]:
Out[11]:
Out[12]:

Out[13]:

 

Out[14]:
  • Veer Kumar

    I am passionate about Analytics and I am looking for opportunities to hone my current skills to gain prominence in the field of Data Science.

    View all posts

Follow Us

Leave a Reply

Your email address will not be published. Required fields are marked *