Matplotlib Side by Side Bar Chart
A bar chart is defined as a chart that consists of rectangular-shaped bars, and the length of the bars represents the relative values of the data points. Python packages not only offer to plot a single bar chart in a plot but also to plot multiple bar charts side by side in the exact figure. These are extremely useful for comparing a similar class of data over some other parameter.
In this article, we will learn how to plot multiple sidebars in python. or, in other words, how to plot side by side bar chart.
Simple Side by Side Bar Chart:
We can add simple side-by-side bar charts using the bar functions in the matplotlib library. We can use the bar() function available in matplotlib to plot the bars. But we need to pass multiple such bar() functions with proper arguments and attributes to plot the side of the bar by the side. Also, we need to slightly displace the bars from each other from the central position so that the bars do not overlap. Otherwise, stacked bars are formed from the code.
Example (1)
#import all the necessary packages and libraries
import matplotlib.pyplot as plt
import numpy as np
#creating the grouped_bar function to plot the graph
def grouped_bar(x,y1,y2,width):
#plotting the first bar graph
plt.bar(x-0.25,y1,width=width,color="purple")
#plotting the second bar graph
plt.bar(x+0.25,y2,width=width,color="green")
#creating the title to the plot
plt.title("Annual profit of a company")
#creating the label along x axis
plt.xlabel("year")
#creating label along y axis
plt.ylabel("profit in million dollars")
#creating legends
plt.legend(["GPAY","PHONEPE"])
#creating the main() function
def main():
#creting data points for the x values
x=np.arange(2012,2022,1)
#creating data points for the first bar graph
y1=[185,175,147,172,143,138,177,156,154,156]
#creating data points for the second bar graph
y2=[134,167,144,153,184,193,186,104,136,145]
#specifying the width of the bars(combined)
width=0.5
#calling the function
grouped_bar(x,y1,y2,width)
#calling the main() function
if __name__ == "__main__":
main()
Output
Explanation
- We first imported all the necessary libraries and modules in the code using the import statement of python. We have used the aliasing method for convenience.
- Next we created a user-defined function called grouped_bar() and it takes four arguments namely x,y1,y2, and width. Under this function, we have used the plt.bar() function to plot the bars. We have subtracted some numbers from the “x” values so that the bars are distinguishable and they do not form any stacked bar instead. We passed the width attribute and passed the value of width as its value. We also set the color to the bar using the color attribute to the function.
- We plotted the two bar graphs side by side, and then we provided the title to the plot, labels to the plot, and legends to the plt using the title(),xlabel(), ylabel(), and legend() functions.
- Next, we created the main() function, which is the driving code of the program. Under this function, we have created the values of x using the numpy library. We have used the np.arange() function for the same. We also created two list variables, “y1” and “y2“. Then set the width variable under the function. We finally called the grouped_bar() function and passed all the necessary arguments to the function.
- Next, we declared the main() function as the driving code of the program using the following lines of code:
if __name__ == “__main__”:
main ()
Creating Side by Side Horizontal Bar Chart
The horizontal bar chart is a type of chart in which rectangular bars represent the data points values. We can also create side by side horizontal bar chart using the matplotlib library. We can do this by using the barh() function instead of the bar() function of the matplotlib. We can also specify other parameters and attributes to the functions to set titles, legends, and labels to the plot.
Example (2)
#import all the necessary libraries
import matplotlib.pyplot as plt
import numpy as np
#creating the horizontal_bar function
def horizontal_bar(y,x1,x2,width):
#plotting the first horizontal_bar
plt.barh(y-0.25, x1,height=0.5,color='purple')
#plotting the second horizontal_bar
plt.barh(y+0.25, x2,height=0.5,color="orange")
# setting label of y-axis
plt.ylabel("year")
# setting label of x-axis
plt.xlabel("salary offered to employees in two companies")
#setting title to the graph
plt.title("Horizontal stacked bar graph")
plt.legend(["facebook","microsoft"])
plt.show()
#creating the main() fucntion
def main():
#dcreating the value for y.
y=np.arange(2015,2021,1)
# creating the values for the x axis.
x1=[52000,85000,75000,35000,45000,55000,]
x2=[89000,45000,78000,56000,78000,47000]
width=0.4
horizontal_bar(y,x1,x2,width)
#calling the main() function.
if __name__ == "__main__":
main()
Output
Explanation
- First, we imported all the necessary libraries and modules into the code using the python import statement.
- We then created a user-defined function called horizontal bar(), which takes four arguments: y,x1,x2, and width. We have passed the value of y and x1 for the first horizontal bar chart. We have subtracted “0.25” from the values of y so that the bar charts are separated from each other. Otherwise, the bar chart formed will be a stacked bar chart on each other. Additionally, we have also passed the color and height argument to the function.
- Next we passed labels, title and legends to the plot using the xlabel(), ylabel(), title() and legend() functions respectively. We used the plt.show() function to display the plot. However, in Jupyter notebook, this command is optional.
- Next, we created the user-defined main() function, a void function. It is the main driving code of the program.
- Under the main() function, we have created the value for the variable y using the np.arange() function. We have passed 2015,2021,1 as the three arguments to the function.2015 represents the starting number for the numpy array element.2021 is the end number to consider. The 1 represents the steps along each iteration.
- For the values of x for the two horizontal bars, we used to list objects instead of numpy arrays.
- We also specified values for the width variable. Under the main() function, finally, we called the horizontal_bar() function and passed the necessary arguments.
- Finally, using the following lines of codes, we declared the main() function as the driving part of the code.
if __name__ == “__main__”:
main ()
Creating Side by Side Bar Chart Using Pandas Library
We can also create side-by-side bar charts using the pandas library. The pandas are a trendy python package beneficial for the data visualization tool. We can create almost all charts using the pandas library, just like the matplotlib library. First, we need to create a data frame to plot the data. We can do this by using the DataFrame() function of the pandas library.
Also, we can pass other arguments to the plot using the pandas library to specify the title, labels, etc., to the figure.
Example (3)
#import all the necessary packages and libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#creating the grouped_bar function to plot the graph
def grouped_bar():
#creating data points
df=pd.DataFrame([["Nvidia",100,233,456,434],],columns=["company","2012","2014","2016","2018"])
#plotting the data frame in using pandas
df.plot(x="company",kind="bar",title="Net profit of companies over the years.")
#creating the main() function
def main():
#calling the grouped_bar() function
grouped_bar()
#creating the main() function
if __name__ == "__main__":
main()
Output
Explanation
- We first imported the three required python packages into our code using the import statement. We have imported matplotlib, numpy, and the pandas library and applied the technique of aliasing names. If you do not have pandas installed in your system, then open the terminal and type the following command to install pandas:
pip install pandas
- We now created a user-defined function called grouped_bar() which does not takes any arguments. Under this function, we have created a data frame using the DataFrame() function of the pandas library.
- We have created a list-like object to pass the column name and the y-axis values of the bars. We used the column attribute to pass the columns and the values along the x-axis.
- Next, we used the df.plot() function to plot the data frame. We passed company as the value of the x attribute. We used kind=” bar” to specify bar charts for plotting the graphs. If we do not specify this command, then by default, we will get a line chart instead of a bar chart.
- Next, we created the main() function, which is the main driving part of the code. We called the grouped_bar() function under this main() function.
- Finally, we declared the main() function as the main() part of the code using the following lines of codes:
if __name__ == “__main__”:
main ()
Conclusion
This article taught us how to plot side-by-side bar charts in python using the matplotlib and the pandas libraries. We have seen that to plot side-by-side bar charts in matplotlib by subtracting and adding some numbers from the data points and specifying the width of the bars.
The readers are, however, encouraged to look up the python matplotlib and the pandas library to know more about the associated functions and attributes.