Open In App

Stacked bar plot Using Plotly package in R

Improve
Improve
Like Article
Like
Save
Share
Report

 In general, the bar plots are used to plot the categorical data. The stacked bar plot is a type of bar plot which is used to visualize the data effectively in the same bar by plotting them in a stacked manner. These are mostly used when one wants to summarize similar kinds of data by plotting a single graph. In R Programming the stacked bar plots can be plotted using the plot_ly() function of the plotly package as follows…

Syntax: plot_ly(df,type,marker,labels,values) %>% layout() %>% add_trace()

Where,

  • df – data frame
  • type – used to specify the type of plot we want to visualize
  • marker – used to mark the plot with different colors using color attribute
  • labels – names of categorical variables in the dataset
  • values – values of the columns in the dataset that we want to plot are specified here (optional)
  • layout() –  this function is used to change the layout as required (like assigning a title to the plot)
  • add_trace() – this function is used to append similar new traces to existing dimension

Let’s install and load the Plotly library with the help of the below commands

install.packages("plotly")
library(plotly)

Stack bar plot for two columns 

In this, we will be creating a data frame that contains 2 columns and then we will be using the Plotly module to plot the stacked bar plot.

R




# Creation of sample data frame (Placement Statistics)
data <- data.frame(
  Branches<-c('CSE','ECE','MECH','EEE','CIVIL'),
  Placements_2021 <-c(99,98,89,90,75),
  Placements_2022 <- c(95,94,93,85,77))
 
# Plotting the stacked bar plot using plot_ly
fig <- plotly::plot_ly(data,x = ~Branches,
                       y=~Placements_2022, type = 'bar', name = '2022') %>%
       add_trace(y=~Placements_2021,name = '2021') %>%
       layout(yaxis = list(title = 'Placements_Count'),
              barmode = 'stack',title="Placement Statistics")
fig


Output:

Stacked bar plot Using Plotly package in RGeeksforgeeks

Stacked bar plot Using Plotly package in R

  • This code represents the placement statistics for various branches. Branches, Placements_2021, and Placements_2022 are its three columns. The number of placements in each branch for 2021 and 2022 is indicated.
     
  • The plot_ly function is used in this section of code to generate a stacked bar plot. The branches on the x-axis are specified by the x parameter, which is set to Branches. The placement counts for the corresponding years are represented by the values of the y argument, which is set to “Placements_2022” for the first add_trace call and “Placements_2021” for the second. To specify that it is a bar plot, the type argument is set to “bar”.
     
  • To alter the look and layout of the plot, utilize the layout function. The “Placements_Count” label is set on the y-axis via the y-axis parameter. The bars are stacked on top of one another using the bar mode option, which is set to “stack”. The plot’s title is changed to “Placement Statistics” using the title argument.

Finally, the plot is stored in the fig object, which can be shown by typing fig in the R console.
 

Stack bar plot for more than two columns

We can also implement the stack bar plotting for more than 2 columns. Let’s see the code for it.

R




# Creation of sample data frame (Student Statistics)
data <- data.frame(
  Languages<-c('Python','R','C++','Java','Ruby'),
  Batch_2020 <-c(199,398,319,910,735),
  Batch_2021 <- c(952,942,933,851,771),
  Batch_2022 <- c(1022,982,983,811,721))
 
# Plotting the stacked bar plot using plot_ly
fig <- plotly::plot_ly(data,x = ~Languages,y=~Batch_2020,
                       type = 'bar', name = '2020') %>%
       add_trace(y=~Batch_2021,name = '2021') %>%  
        add_trace(y=~Batch_2022,name = '2022') %>%
       layout(yaxis = list(title = 'Students_Count'),
              barmode = 'stack',title="Student Statistics")
 
fig


Output:

Stacked bar plot Using Plotly package in RGeeksforgeeks

Stacked bar plot Using Plotly package in R

  • This code generates a data frame called data that contains statistics on students studying various programming languages. Languages, Batch_2020, Batch_2021, and Batch_2022 are its four columns. The number of students in each batch year is correlated with each language.
     
  • This section of code generates a stacked bar plot using the plot_ly function from Plotly. The programming languages are represented on the x-axis by the value of the x parameter, which is set to Languages. For the first, second, and third add_trace calls, the y argument is set to Batch_2020, Batch_2021, and Batch_2022 respectively. These show how many students are in each batch year.
     
  • To specify that it is a bar plot, the type argument is set to “bar”. A new bar trace representing a different batch year is added to the plot with each call to add_trace.
     
  • To alter the look and layout of the plot, utilize the layout function. ‘Students_Count’ is the title that is set for the y-axis by the y-axis argument. The bars are stacked on top of one another using the bar mode option, which is set to “stack”. The plot’s title is changed to “Student Statistics” using the title argument.

Horizontal Stack bar plot for more than two columns

Now we can try to plot a stack bar plot in the horizontal direction.

R




# Creation of sample data frame (Student Statistics)
data <- data.frame(
  Languages = c('Python', 'R', 'C++', 'Java', 'Ruby'),
  Batch_2020 = c(199, 398, 319, 910, 735),
  Batch_2021 = c(952, 942, 933, 851, 771),
  Batch_2022 = c(1022, 982, 983, 811, 721)
)
 
# Plotting the horizontal stacked bar plot using plot_ly
fig <- plotly::plot_ly(data, y = ~Languages, x = ~Batch_2020,
                       type = 'bar', name = '2020', orientation = 'h') %>%
  add_trace(y = ~Languages, x = ~Batch_2021, name = '2021', orientation = 'h') %>%
  add_trace(y = ~Languages, x = ~Batch_2022, name = '2022', orientation = 'h') %>%
  layout(
    xaxis = list(title = 'Students Count'),
    barmode = 'stack',
    title = "Student Statistics",
    yaxis = list(title = 'Languages'),
    legend = list(title = 'Batches', orientation = 'v',
                  xanchor = 'center', x = 0.5, y = -0.2)
  )
 
fig


Output:

Horizontal Stacked bar plot Using Plotly package in RGeeksforgeeks

Horizontal Stacked bar plot Using Plotly package in R

  • To make the bars display horizontally, the y and x inputs inside plot_ly() and add_trace() have been switched. 
     
  • Now, the x argument denotes the equivalent Batch values, and the y argument stands in for the Languages.
     
  • In order to specify the horizontal orientation of each bar, the orientation parameter has been set to ‘h’.
    In order to reflect the change in orientation, the names of the x-axis and y-axis have been switched.
     
  • The vertical alignment symbol (‘v’) has been added to the legend orientation.
    Other design and title alterations have been kept.
     


Last Updated : 13 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads