How do you plot a stacked bar chart in python using seaborn?

import pandas as pd

import matplotlib.pyplot as plt

df = pd.DataFrame({'High Temp': [28, 30, 34, 38, 45, 42,

                                 38, 35, 32, 28, 25, 21],

                   'Low Temp': [22, 26, 30, 32, 41, 38,

                                32, 31, 28, 22, 15, 15],

                   'Avg Temp': [25, 28, 32, 35, 43, 40,

                                35, 33, 30, 25, 20, 18]},

                  index=['Jan', 'Feb', 'Mar', 'Apr', 'May',

                         'Jun', 'Jul', 'Aug', 'Sep', 'Oct',

                         'Nov', 'Dec'])

df.plot(kind='bar', stacked=True, color=['red', 'skyblue', 'green'])

plt.xlabel('Months')

plt.ylabel('Temp ranges in Degree Celsius')

plt.title('Monthly Temperatures in a year')

Data exploration is something that we all like doing. Exploratory data analysis is the process of displaying data and understanding or extracting important information. Data can be displayed in many different ways. A stacked bar plot is a useful graph that is used in a variety of applications and presentations. We will learn how to comprehend and build stacked bar plots using Python in this article.

What is A Stacked Bar Plot in Seaborn

A stacked bar plot is a visual representation of a data set in which the category is highlighted with certain shapes such as rectangles. The data provided in the dataset is represented by the length and heights of the bar chart. In a stacked bar plot, one axis includes the proportion of counts associated with a specific classification of a column in the dataset, while the other axis represents the values or counts connected with it. Stacked bar plots could be represented horizontally or vertically. The vertical bar chart is known as a column chart.

A stacked bar plot is a type of graph where each bar is graphically divided into sub bars to show numerous columns of data at the same time.

It’s also worth remembering that a bar plot only shows the mean (or another estimator) value, whereas showing the range of possible values through each scale of the categorical data may be more helpful in many circumstances. Other plots, such as a box or a violin plot, would be more appropriate in this scenario.

Syntax of the Seaborn Stacked Bar Plot

The syntax of Seaborn’s stacked bar plot function is extremely simple.

DataFrameName.plot( kind=’bar’, stacked=True, color=[color1,color2,...colorn])

Here is the DataFrameName in the Plotting data set. This is considered a wide form if x and y are not present. Aside from that, it will be long-form inside this DataFrameName. The plot method must be set to stacked=True to plot the Stacked Bar layout. We may also pass a color list, which we used to color separately every sub bar in a bar. Some other optional parameters also play a significant role in plotting the stacked bar plots.

order, hue_order: The categorical levels must be plotted in order; otherwise, the levels are assumed from the data items.

estimator: Within each categorical bin, use this statistical function to estimate.

ci(float, sd, None): The width of the confidence intervals should be drawn around the estimated values if “sd,” skip the scaling and show the observations’ standard deviation instead. There will be no bootstrapping and no error bars if None is specified.

n_boot(int): The frequency of bootstrap cycles to use when calculating statistical models is defined.

orient: The plot is oriented in a certain way (vertical or horizontal). This is normally inferred from the input variables’ types, but it can be utilized to clarify uncertainty in which both x and y variables are integers or when visualizing a wide-form data.

palette: Colors to utilize for various hue levels. Should be a dictionary translating hue ranges to matplotlib colors, or anything that color palette() can understand.

saturation: Colors should be drawn at a proportion of the actual saturation large areas profit from moderately de-saturated colors, but unless we want the plot colors to meet the input color specifications exactly, set this to 1.

errcolor: The lines that represent the statistical model are colored differently.

errwidth(float): Line thickness of error bars (and caps).

dodge(bool): Whether or not elements should be moved along the categorized axis when hue nesting is employed.

Example 1:

We have a simple stacked bar plot that shows the sales of the car over different months. We included some libraries which are necessary for this example code. Then, we created a data frame in the variable “df”. We have three fields with the car name that have different percentages of sales per year and in the index field, we included the month names. Then, we created the stacked bar plot by calling the df.plot and passed the parameter kind as a bar, and stacked the value to true inside it. After that, we assigned the label to the x and y-axis and also set the title for the stacked bar plot.

How do you plot a stacked bar chart in python using seaborn?

The visual representation of the stacked bar plot is as follows:

How do you plot a stacked bar chart in python using seaborn?

Example 2:

The following code demonstrates how to add axis titles, and an overview title, and on how to rotate the x-axis and y-axis labels for better readability. We created the data frame of the laborers with the morning and evening shifts over the days inside a variable “df”. Then, we created a stacked bar plot with the df.plot function. After that, we set the title for the plot as ‘Company Labors’ with the font size. The labels for the x-axis and y-axis id are also given. In the end, we gave an angle to the x and y variables which rotates according to that angle.

How do you plot a stacked bar chart in python using seaborn?

The stacked bar plot with the rotational x and y labels is shown in the figure as follows:

How do you plot a stacked bar chart in python using seaborn?

Example 3:

We may use the same bar plot to display a set of categorical values. The end outcome will not have a stacked appearance, but will instead depict the observations on a single graph with several bars. In the example code, we set the data frame which has the data of the mobile having different rates on different days. This plot shows the rates of two mobile simultaneously as we set the x and y variable parameter in the seaborn bar plot function with the hue set as mobile.

How do you plot a stacked bar chart in python using seaborn?

The plot is visualized with the two bars in the following graph figure:

How do you plot a stacked bar chart in python using seaborn?

Conclusion

Here, we briefly explained the stacked bar plot with the seaborn library. We showed the stacked bar plot with different visualization of the data frames and also with different styling of x and y labels. The scripts are simple to comprehend and learn using the Ubuntu 20.04 terminal. All three examples can be changed as per the work needs of users.

About the author

Hello, I am a freelance writer and usually write for Linux and other technology related content

How do I make a stacked bar chart in Seaborn?

A stacked Bar plot is a kind of bar graph in which each bar is visually divided into sub bars to represent multiple column data at once. To plot the Stacked Bar plot we need to specify stacked=True in the plot method. We can also pass the list of colors as we needed to color each sub bar in a bar.

How do you plot a stacked bar plot in Python?

Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack..
Import Library (Matplotlib).
Import / create data..
Plot the bars in the stack manner..

How do you plot a bar chart in Seaborn?

Seaborn..
x, y : This parameter take names of variables in data or vector data, Inputs for plotting long-form data..
hue : (optional) This parameter take column name for colour encoding..
data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting..

How do you show bar chart values in Seaborn?

In seaborn barplot with bar, values can be plotted using sns. barplot() function and the sub-method containers returned by sns. barplot(). Import pandas, numpy, and seaborn packages.