Open In App

How to Make a Histogram with ggvis in R

Improve
Improve
Like Article
Like
Save
Share
Report

In R Programming ggvis is the successor of ggplot package which is used to visualize data. Mainly ggvis package is introduced to plot HTML graphs so that these plots can be used in shiny web applications with short efforts. The layer_histogram() in ggvis is used to ensure the plot is a Histogram Plot.

Syntax of layer_histograms() function of ggvis package

Syntax: df %>% ggvis(~df) %>% layer_histograms(boundary)

Where,

  • df : The dataframe that need to be plotted.
  • ~df: The Column of the data frame to be plotted is specified here.
  • boundary: It is used to specify boundary of bar in the histogram.

Example 1: Creating Histogram with ggvis

Install and load the required package and Load or Create the dataset as a Dataframe. Here, we are using the default dataset iris for our article, you are free to choose any dataset to plot the Histogram with ggvis in R. Using the layer_histograms() function of ggvis package we are going to plot the Histogram Plot.

R




# Install ggvis package
install.packages("ggvis")
# Load the installed package
library(ggvis)
  
# Load the default dataset (iris)
data(iris)
# Convert that dataset to data frame
df <- data.frame(iris)
  
iris %>% ggvis(~iris$Sepal.Length) %>% 
            layer_histograms(boundary = 1)


Output:

How to Make a Histogram with ggvis in R

 

Example 2: Add Label and Title

The plot can also be customized by adding x, and y-axis labels and a title to the plot as follows

R




iris %>% ggvis(~iris$Sepal.Length,fill:="blue") %>% 
  layer_histograms() %>%
  add_axis("x", title = "Sepal Length") %>%
  add_axis("y", title = "Counts") %>%
  add_axis("x",title = "Histogram Plot using ggvis",orient="top")


Output:

How to Make a Histogram with ggvis in R

 

Example 3: Adjust width of bin

Adjustment of the width of the bars can also be done using the width parameter in the layer_histograms() function to make sure the graph is precise with less number of bins. As there were no parameters like in ggplot to specify the number of bins in ggvis the width of the bin [ The individual bars are known as Bins] is inversely proportional to the number of bins here.

R




library(ggvis)
iris %>% ggvis(~iris$Sepal.Length,fill:="blue") %>% 
  layer_histograms(width=1) %>%
  add_axis("x", title = "Sepal Length") %>%
  add_axis("y", title = "Counts") %>%
  add_axis("x",title = "Histogram Plot using ggvis",orient="top")


Output:

How to Make a Histogram with ggvis in R

 



Last Updated : 30 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads