Python Matplotlib Plotting Barchart

This is our fourth article in Python Matplotlib, in this article we are going to learn about Matplotlib Plotting Barchart. a bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a column chart. you can read the previous articles for Python Matplotlib in the below links.

 

 

Matplotlib Tutorials For Beginners

1: Matplotlib Introduction & Installation 

2: Matplotlib Plotting Multiple Curves

3: Matplotlib Plotting Scatter (Points)

 

 

 

So now let’s create our first Barchart in Matplotlib.

 

OK in the above code first of of all we have imported our matplotlib library, after that for each value in the list data, one vertical bar is shown. The pyplot.bar() function receives two arguments—the x coordinate for each bar and the height of each bar. Here, we use the  coordinates 0, 1, 2, and so on, for each bar, which is the purpose of range(len(data)).

 

 

 

If you run the code this will be the result

Python Matplotlib Plotting Barchart
Python Matplotlib Plotting Barchart

 

 

 

 

Controlling Thickness of the Bar

So by default a bar have thickness of 0.8 units. because we put a bar at each unit length,
we have a gap of 0.2 between them. You can, of course, fiddle with this thickness parameter.
for instance, by setting it to 1.

 

 

 

 

 

OK now in the code, the bars have no gap between them.

Matplotlib BarChart
Matplotlib BarChart

 

 

 

 

 

Horizontal Bars

Also you can plot horizontal bars using the barh() function, which is the strict equivalent of  bar(), apart from giving horizontal rather than vertical bars.

 

 

 

 

 

 

So now if you run the code, you can see that we have horizontal bar instead of vertical bar.

Python Matplotlib Horizontal Bar
Python Matplotlib Horizontal Bar

 

 

 

 

 

Plotting Multiple BarCharts

Also you can plot multiple BarCharts in Matplotlib. we can plot multiple bar charts by playing with the thickness and the positions of the bars  .

 

 

 

 

 

 

If you run the code this will be the result

Matplotlib Multiple BarChart
Matplotlib Multiple BarChart

 

 

 

 

 

Stacked BarCharts 

Stacked bar charts are of course possible by using a special parameter from the pyplot. bar() function.

 

 

 

OK in the above code we have imported our matplotlib library , also  The optional bottom parameter of the pyplot.bar() function allows you to specify a  starting value for a bar. the first call to pyplot.bar() plots the green bars. the second call to pyplot.bar() plots the yellow bars.

 

 

 

 

If you run the code this will be the result

Matplotlib Stacked BarChart
Matplotlib Stacked BarChart

 

 

 

 

 

 

 

 

Subscribe and Get Free Video Courses & Articles in your Email

 

Share via
Copy link
Powered by Social Snap
×