How to create horizontal stacked bar chart using ggvis in R?
In this article, we are going to learn how to create a horizontal stacked bar chart using ggvis in R programming language.
ggvis package
A ggvis package is a tool used for data visualization in R. It is used to create visual interactive graphics tools for data plotting and representation. The package can be installed into the working space using the following command :
install.packages("ggvis")
The ggvis method in the ggvis package is used to start ggvis graphical window. The ggvis method has the following syntax :
Syntax: ggvis( data , mp1, mp2.,)
Arguments :
- data – The dataset to plot
- mp1, mp2,.. – The map variables to plot
layer_rects() method
The layer_rects() method is used to specify any of the two arguments like height, y or y2, and two of the following arguments, width, x, or x2. In order to create a horizontal stacked bar chart, we use x2=0 and specify height equivalent to the default band() method.
Create a horizontal bar chart
To create a horizontal bar chart we need a data frame so we have created a data frame that is used to create a horizontal bar chart with the help of ggvis() method of ggvis library.
R
# Importing ggvis package library ( "ggvis" ) # Declaring a data frame data_frame <- data.frame (col1 = c ( "a" , "b" , "c" , "d" , "e" ), col2 = c (1,2,3,4,5), col3 = c ( "Green" , "Orange" , "Green" , "Green" , "Orange" )) # Printing the data frame print ( "Data Frame" ) print (data_frame) # Plotting the data data_frame %>% ggvis (x =~col2, y=~col1, fill =~ col3) %>% layer_rects (x2 = 0, height = band ()) |
Output:
[1] "Data Frame" > print (data_frame) col1 col2 col3 1 a 1 Green 2 b 2 Orange 3 c 3 Green 4 d 4 Green 5 e 5 Orange
Explanation :
The col2 values are taken as x coordinates and the col1 values of the data frame are taken as y coordinates of the plot constructed. The colors are then assigned based on the col3 values depicted by the fill parameter of the ggvis() method.
Create a horizontal stacked bar chart
The same procedure is followed to create a horizontal bar chart and to create a stacked bar chart we have the group_by() method which is used to create segments based on the values mapped to individual groups. The following code snippet indicates the grouping of the data by col3 values and therefore, creates three groups. Which results in the horizontal stacked bar chart.
R
# Import ggvis library library ( "ggvis" ) # Declaring a data frame data_frame <- data.frame (col1 = c ( "a" , "b" , "a" , "e" , "a" , "b" , "a" , "e" , "a" , "b" ), col2 = c (1:10), col3 = c (1,2,2,4,9,1,4,2,2,1)) # Printing the data frame print ( "Data Frame" ) print (data_frame) # Plotting the data data_frame %>% ggvis (x =~col2, y=~col1, fill =~ col3) %>% group_by (col3)%>% layer_rects (x2 = 0, height = band ()) |
Output:
[1] "Data Frame" > print (data_frame) col1 col2 col3 1 a 1 1 2 b 2 2 3 a 3 2 4 e 4 4 5 a 5 9 6 b 6 1 7 a 7 4 8 e 8 2 9 a 9 2 10 b 10 1