Home Python How to Plot a Bar Graph Using Python matplotlib Library

How to Plot a Bar Graph Using Python matplotlib Library

Data Visualization is one of the most important things for a data scientist or anyone working or analyzing data. Visual data is easier to understand by a person than raw data, so it is more important to visualize data while performing presentations or analyzing data. We can also take out powerful insights from the raw data if visualized adequately.

There are two popular libraries for data visualization in python: matplotib and seaborn. This tutorial will use the matplotlib library of python to create amazing bar graphs. For writing code, it is recommended to use an IDE. Here I use the open-source Visual Studio Code; you can use it or choose any of the best IDEs.

Installation

To follow this tutorial, python must be installed in your system. If you don’t have python installed or have a problem installing python, you can refer to our guide on installing python on Linux. We also need to install the matplotlib library of python, one of the most popular data visualization libraries of python. We can install the matplotlib library in python by using the pip package manager by just running the following command in the terminal. It is also recommended to create a virtual environment for this article to have no problem with your main Python installation and dependencies.

pip install matplotlib

On running the above command in the terminal, we will have matplotlib install in our python environment. You can check your installation by firing up the python shell and run the following code.

import matplotlib

If the above code runs without an ImportError, then the matplotlib library has been successfully installed in your system.

Creating Bar Graphs

We have all the dependencies installed. Now let us see how we can create bar graphs. We can use the bar() function of the matplotlib.pyplot to plot the bar graph easily. The below code shows how we can plot the data present in two lists using the bar() function.

# importing the required libraries
import matplotlib.pyplot as plt
# creating the X Coordinate data as a python list 
list1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
# creating the Y Coordinate data as a python list
list2 = [100, 50, 100, 80, 60, 30, 60, 88, 30]
# plotting the bar graph
plt.bar(list1, list2)
# displaying the bar graph
plt.show()

In the above code, we first imported the matplotlib.pyplot module has a bar() function that can be used to plot a bar graph. Then we created two lists, one having all the characters between A to I, and the other has some numbers. We use the bar() method of matplotlib.pyplot with the two lists as arguments that will create the bar graph according to the list’s data. Then we use the show() method of matplotlib.pyplot to display the bar graph.

Output:

creating a bar graph
creating a bar graph

Plotting Horizontal Bar Graph

To create a horizontal bar graph, we need to use the barh() function of the matplotlib library. The below code block shows a practical illustration of plotting a horizontal bar graph.

# importing the required libraries
import matplotlib.pyplot as plt
# creating the data as python lists 
list1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
list2 = [100, 50, 100, 80, 60, 30, 60, 88, 30]
# plotting the bar graph in horizontal direction
plt.barh(list1, list2)
# displaying the bar graph
plt.show()

In the above code, we have created two lists and then use the barh() function of the matplotlib.pyplot with the two lists as parameters. The barh() function is almost similar to the bar() function, but instead of plotting the bar graph vertically, it plots the bar graph horizontally.

Output:

plotting horizontal bar graphs
plotting horizontal bar graphs

Customization

We can also customize the plotting of bar graphs by changing their color, setting the plot’s height and width, etc. Let us see how we can easily do such customization using the matplotlib library.

Changing the Color

In the bar graphs that we have plotted till now, we can see that the color of the bar is blue, which is the default color for the bars. We can easily change this color to some other color by specifying the color parameter of the bar() or barh() function. See the below code for example.

# importing the required libraries
import matplotlib.pyplot as plt
# creating the X Coordinate data as a python list 
list1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
# creating the Y Coordinate data as a python list
list2 = [100, 50, 100, 80, 60, 30, 60, 88, 30]
# plotting the bar graph
# with the color red 
plt.bar(list1, list2, color="red")
# displaying the bar graph
plt.show()

In the above code, we first imported the pyplot file of the matplotlib library and then used its bar() function with the two lists as the argument. We also use the bar’s color parameter () function with the value with the string “red,” which changes the color of the bars from the default blue to red. Then we use the show() function of the matplotlib.pyplot to display the bar graph.

Output:

changing the color of bar graph plot
changing the color of bar graph plot

In the previous code, we have given the color name to the color parameter of the bar() function. Still, we can also specify the color by providing the hexadecimal values of that color. See the below code for an illustration.

# importing the required libraries
import matplotlib.pyplot as plt
# creating the X Coordinate data as a python list 
list1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
# creating the Y Coordinate data as a python list
list2 = [100, 50, 100, 80, 60, 30, 60, 88, 30]
# plotting the bar graph
# with the color green by providing hexadecimal code
# of the color  
plt.bar(list1, list2, color="#0f0")
# displaying the bar graph
plt.show()

The above code is almost similar to the previous code, but instead of giving the color name, we have provided the hexadecimal code of that color. We have given color code #0f0 in the above code block, which means that the color has the hexadecimal value #0f0, i.e., green, will be used for the bars.

Output:

changing the color of bar graph by providing hexadecimal values of the color
changing the color of bar graph by providing hexadecimal values of the color

Height and Width

We can also specify the height and width of the bars of the bar graph. To do so, we need to use the width and height parameters of the bar() and barh() function. The below code shows a practical demonstration of setting the width of the bars of the bar graph.

# importing the required libraries
import matplotlib.pyplot as plt
# creating the X Coordinate data as a python list 
list1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
# creating the Y Coordinate data as a python list
list2 = [100, 50, 100, 80, 60, 30, 60, 88, 30]
# plotting the bar graph
# with custom width
plt.bar(list1, list2, color="#0f0", width=0.35)
# displaying the bar graph
plt.show()

In the above code, we use the width parameter of the bar() function and pass the value of 0.35 to set the width of the bar. We can also provide the height of the bar using the height parameter in a similar way.

Output:

Observe in the below image that the width of the bars was decreased compared to the previous graphs.

setting the width and height of the bar graph
setting the width and height of the bar graph

Setting Labels and Title

The bar graphs that were plotted until now do not have any labels or titles indicating the graph data. We can also set the label to the graph so the person who sees the graph can recognize it without any problem. The below code shows how we can set labels and a bar graph title.

# importing the required libraries
import matplotlib.pyplot as plt
# creating the X Coordinate data as a python list 
list1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
# creating the Y Coordinate data as a python list
list2 = [100, 50, 100, 80, 60, 30, 60, 88, 30]
# Giving the title of bar chart
plt.title("Sample bar chart")
# Setting the X and Y labels
plt.xlabel("X axis data")
plt.ylabel("Y axis data")
# plotting the bar graph
plt.bar(list1, list2, color="#0f0", width=0.35)
# displaying the bar graph
plt.show()

In the above code, we have used the title(), xlabel(), ylabel() method of the matplotlib.pyplot module to set the title, label of the X coordinate, the label of the Y coordinate respectively.

Output: We can see from the below image that the X-label, Y-label, and the title were displayed at their respective position on the bar graph.

setting the labels and titles to the bar graph
setting the labels and titles to the bar graph

Saving the Bar Graph as Image

We have seen how to plot a bar chart and display it, but we can also save the bar chart as an image by using the matplotlib library. The below code shows a practical illustration of how to perform that.

# importing the required libraries
import matplotlib.pyplot as plt
# creating the data as python lists 
list1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
list2 = [100, 50, 100, 80, 60, 30, 60, 88, 30]
# plotting the bar graph in horizontal direction
plt.barh(list1, list2)
# saving the image of the bar graph
plt.savefig("image.png")

In the above code, we used the savefig() function of matplotlib.pyplot with the image’s name as an argument. If we run the above code, we will have a new image created in the current working directory with the name image.png, and it contains the bar graph of the data we passed in the argument of the barh() function.

Conclusion

In this article, we have seen how to plot bar graphs easily in python using the matplotlib library. Plotting bar graphs will help any data visualizations and extract insights from that data and can also be used for better-presenting data to clients. You may also refer to our step by step guide on creating and reading QR codes in python.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More