How Can We Help?
Matplotlib is a compelling python library used for many data visualization tools especially plotting graphs and animations, graphics, etc. The bar chart is special in matplotlib, which is believed to be the best chart for comparison purposes. We can not only add one bar to the matplotlib bar chart, but we can add multiple bar charts to the plot.
In this article, we will learn how to plot multiple bar charts in python.
Matplotlib Multiple Grouped Bar Chart:
Grouped multiple charts mean a bar chart that resides side by side in the plot. Plotting the multiple grouped bar chart can be quickly done with the help of the bar () function of matplotlib.pyplot library. Only we need slight modification in the code to insert the required number of multiple plots in the figure.
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.2,y1,width=width)
#plotting the second bar graph
plt.bar(x+0.2,y2,width=width)
#creating the title to the plot
plt.title("Annual profit of a company")
#creating the label along the x-axis
plt.xlabel("year")
#creating labels along the y axis
plt.ylabel("profit in million dollars")
#creating legends
plt.legend(["Intel","AMD"])
plt.show()
#creating the main() function
def main():
#creating data points for the x values
x=np.arange(2012,2022,1)
#creating data points for the first bar graph
y1=[165,175,144,122,143,138,167,156,154,186]
#creating data points for the second bar graph
y2=[34,67,44,53,84,93,86,104,136,145]
#specifying the width of the bars(combined)
width=0.4
#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 with the help of the import statement of python. We imported the matplotlib.pyplot and the numpy library using alias names as plt and np.
- Next, we created a user-defined function called the grouped_bar () function. The function will take four parameters: x, y1, y2, and width. Under this function, we have plotted the grouped bar chart using the bar () function of the matplotlib.pyplot. We passed the x as the parameter and subtracted 0.3 from the value of x. We passed the y1 as the value, the y-axis for the bar, and the width argument for the width of the bars.
- We also have the set title for the plot using the title () function. After that, we provided labels to the figure using the xlabel () and ylabel () functions. We then provided legend() to the figure using the legend() function.
- We now created the main () function. This is the main piece of the program or the driver code of the program. We created a numpy array to store the value of x. We then created a list of data types for the value of y1 and y2, which we use later to plot the two bar graphs.
- We also set the value for the width of the bars. Under the main () function, we finally called the grouped_bar () function and passed the values of x, y1,y2, and width as the arguments.
Multiple Stacked Bar Charts Using Matplotlib
We can plot multiple stacked bars in matplotlib using the plot function alone. We do not need to use any other changes in the codes. We only need to use the multiple plot() functions to the code and pass necessary valid arguments or parameters to the functions. This can be illustrated in the following examples:
Example (2)
#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 stacked_bar(x,y1,y2):
#plotting the first bar graph
plt.bar(x,y1,color="red")
#plotting the second bar graph
plt.bar(x,y2,color="green")
#creating the title to the plot
plt.title("Annual profit of a company")
#creating the label along the x-axis
plt.xlabel("year")
#creating labels along the y axis
plt.ylabel("profit in million dollars")
#creating legends
plt.legend(["Intel","AMD"])
#creating the main() function
def main():
#creting data points for the x values
x=np.arange(2000,2010,1)
#creating data points for the first bar graph
y1=[65,65,44,22,43,38,67,56,5,56]
#creating data points for the second bar graph
y2=[34,67,4,23,24,53,86,74,75,8]
#specifying the width of the bars(combined)
#calling the function
stacked_bar(x,y1,y2)
#calling the main() function
if __name__ == "__main__":
main()
Output
Explanation
- We first imported all the necessary libraries to the code. We have used the import statement for the same.
- Next, we created a user-defined function called stacked_bar () which takes three arguments, namely x y1 and y2. Under the function, we plotted the bars using the bar () function of the matplotlib library. We passed x, y1, and color for the first bar. We set the color of the first bar as red. Similarly, we created the plot for the second bar and passed similar values. We, however, set the color of the second bar to green.
- Next, we set the title, labels, and legends to the plt using the title (), xlabel (), ylabel(), and the legend() function of the matplotlib library.
- Now we create the main () function in the code. This is called the driving code of the program.
- We created a data point for the variable x using the numpy array.
- We created a list of the values of y1 and y2. We used these as the values for the bars.
- We finally called the stacked_bar () function and passed x, y1, and y2 as the arguments to this function.
- Finally, we called the main () function using the following code:
if __name__ == “__main__”:
main ()
Multiple Horizontal Stacked Bar
We can also plot multiple stacked bars in matplotlib. We can easily do it by passing multiple plot () functions in the exact figure with all valid attributes and factions. We can use all the attributes associated with the bar chart for this type of graph.
Example (3)
#import all the necessary libraries
import matplotlib.pyplot as plt
#creating the horizontal_bar function
def horizontal_bar(y,x1,x2):
#plotting the first horizontal_bar
plt.barh(y, x1)
#plotting the second horizontal_bar
plt.barh(y, x2)
# setting label of the y-axis
plt.ylabel("employees")
# setting label of the x-axis
plt.xlabel("salary")
#setting title to the graph
plt.title("Horizontal stacked bar graph")
plt.show()
#creating the main() function
def main():
#creating the value for y.
y=['john', 'simon', 'smith', 'veda', 'venkat',"perry"]
# crating the values for the x-axis.
x1=[52455,78000,75000,78000,14442,14488]
x2=[45111,71114,57574,47575,54275,55000]
horizontal_bar(y,x1,x2)
#calling the main() function.
if __name__ == "__main__":
main()
Output
Explanation
- We imported the necessary libraries and modules in our code as customary. Here we have imported the matplotlib library using the aliasing name.
- Next, we created a user-defined function named horizontal_bar() which takes three arguments: y,x1, and x2. Under the function, we plotted the horizontal bars using the barh() function of matplotlib. We passed y and x1 for the first horizontal bar and x and y2 for the second horizontal bar.
- We also provided labels and titles to the chart.
- Next, we created the main () function, which is the main driving code of the program. Under this function, we created a list where we stored the name of the employees and named it y.
- Next, we created two lists, x1 and x2, for the values of the two horizontal bar charts. We called the horizontal_bar() function with the necessary arguments passed.
- Finally, we called the main () function using the following command:
if __name__ == “__main__”:
main ()
Multiple Horizontal Charts
We can also easily create multiple horizontal charts in matplotlib with the barh() function. However, we need to change the code slightly for the proper visualization. If we try to plot the bar charts in one figure, then the horizontal bars will be stacked. If we want to display the horizontal bar charts side by side, we need to displace the bars by some reasonable distance. We can achieve the same by creating a numpy array and then subtracting or adding some numbers from the array per the requirements.
This is illustrated in the following code:
Example (4)
#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.3, x1,height=0.4)
#plotting the second horizontal_bar
plt.barh(y+0.3, x2,height=0.4)
# setting label of the y-axis
plt.ylabel("employees")
# setting label of the x-axis
plt.xlabel("salary offered to employees in two companies")
#setting title to the graph
plt.title("Horizontal stacked bar graph")
plt.show()
#creating the main() function
def main():
#creating the value for y.
y=np.arange(2010,2016,1)
# gcreting the values for the x-axis.
x1=[52455,78000,75000,78000,14442,14488]
x2=[45111,71114,57574,47575,54275,55000]
width=0.4
horizontal_bar(y,x1,x2,width)
#calling the main() function.
if __name__ == "__main__":
main()
Output
Explanation
- We imported matplotlib.pyplot and numpy library using their alias names.
- Next, we create a user-defined function called horizontal_bar (), which takes two arguments: y, x1, x2, and width. Under the function, we plotted the horizontal bar chart using the barh () function. We have subtracted 0.3 from the y value of the first bar chart and added the same number to the y value of the second bar chart.
- Note that we also passed another critical attribute to the function: height. This attribute is crucial for correctly visualizing the multiple horizontal bar graph. We then provided labels to the graph using the xlabel () and ylabel() functions. We finally provided the title to the plot and displayed the plot using the plt.show() function. Note that in the Jupyter notebook, we can skip the code plt.show().
- We created the main () function, which is the driving code of the program. Under the function, we created a data point using a numpy array and named it y. We also created two lists, namely x1 and x2. We also set the width value for the height of the graph. Next, we called the horizontal_bar () function using the required arguments passed.
- Finally, we declared the main () function as the driving code of the program using the following lines of code:
if __name__ == “__main__”:
main ()
Plotting Multiple Bar Charts Using Pandas Library:
We can use external libraries in python to plot multiple bar charts. Panadas is a popular data analysis library but also offers the functionality of plotting the data. We only need to use the plot () function of pandas to plot the multiple bar charts in the graph. However, before passing the values as the arguments, it is crucial to create a data frame which is standard practice. This can be easily done by the DataFrame() function of the pandas library itself.
Example (5)
#import the required libraries and modules in the current code.
import pandas as pd
import matplotlib.pyplot as plt
#creating the pandas_plot() function
def pandas_plot(x):
#creating data frame for the plot
df=pd.DataFrame(x)
#plotting using pandas po=lot() function
df.plot(x="name",kind="bar",title="Marks distribution of the students")
#assigning labels along the x-axis
plt.xlabel("Name of the students")
#assigning labels along the y axis
plt.ylabel("Marks of the students")
#creating the main () function
def main():
#creating the value of x
x={"name":["Joe","john","devid","miller"],"Science":[45,56,84,78],"maths":[89,34,32,44]}
#calling the pandas_plot function
pandas_plot(x)
#declearing the main() function as the driving function of the code
if __name__ == "__main__":
main ()
Output
Explanation
- We imported the panda’s library and matplotlib.pyplot library using the import statement.
- Next, we create the horizontal_bar () function, which takes only one parameter, x. We then created the data frame for plotting the graph in the pandas library. We passed x to this function. Next, we used the plot () function to plot the data frame. We passed the value of x as “name”. We passed the value of attribute kind as “bar”. Also, we provided the title to the graph using the title attribute.
- After that, we provided labels to the plot using the xlabel () and the ylabel () function. We can use the pandas and matplotlib library to work on the exact workspace figure.
- We then created the main () function, which is the driving code of the program. Under the main() function, we then created the values of x as data frame format. We made a dictionary object and passed the key’s value as the column’s name. The value is in the form of a list that represents the values of the bars.
- We then called the pandas_plot() function and passed the value of x as the argument.
- We finally declared the main() function as the driving code of the program using the following code:
if __name__ == “__main__”:
main ()
Conclusion
In this article, we learned about how to plot multiple bar charts in python by using different libraries. We used the pandas and the matplotlib library for the same. The matplotlib is more widely used to plot graphs because it is more specifically designed to visualize the plots. In contrast, the primary purpose of the pandas library is for data cleaning, analysis, etc.
We would recommend the users to look up the python matplotlib and pandas libraries to know more about different functions and attributes associated with the same.