Bar Chart in Python

Bar Chart in Python

Bar chart implementation is also very interesting using Matplotlib. In last post we discussed about Line Chart implementation in Python using Matplotlib. So for installation of Matplotlib and to start using it, you can refer Line Chart in Python page.

Now lets focus on Bar Chart Implementation. To generate bar chart using matplotlib you need to call pyplot.bar() function and need to pass minimum x and y co-ordinates values in terms of list. Lets see the example code first.

Bar Chart using Matplotlib

Apart from the basic parameter which is x and y co-ordinates value you can pass the width value, I used 0.5 to keep distance between bar charts. Next parameter we can pass is COLOR. Color can be single value like ‘red’, in this case all the bars color will be of Red color. If you want to appear your bars to be multicolor then you can pass list of colors to color parameter of bar() function. Here four color has been used, so first four will be as is and fifth onward color will get repeated. Lets see the output of above bar chart code.

Multicolor Bar Chart using Matplotlib

That’s it, you can try your own to get this beautiful bar chart using above code.

Line chart in Python

Line chart in Python

Drawing chart in other languages are one of the difficult task and need to do lots of exercise to plot a simple chart. But here in case of Python, plotting a chart is only 2 or 3 lines of job. So lets start to learning line cart plotting in Python.

For doing that you need to install third party library Matplotlip (https://matplotlib.org/ ). You can install matplotlib using pip command in the command prompt. Steps to import and use Matplotlip –

  1. You need to open command prompt and type below command on command line if pip package is already installed in your machine and path of python home directory is already set in your system.
  2. type pip install matplotlib on the command prompt
  3. It will start downloading matplotlib from internet and will take few minutes to get it install.
  4. If you are getting success message on command prompt then you are done with installing.

Next step is to import matplotlib. In your program you need to write import matplotlib.pyplot as pyplot in very first line of your program to use pyplot facilities in your program. Here is the sample code to create line chart.

Code to plot Line Chart

If you will see this code, First line is importing matplotlib.pyplot after that second line is plotting linechart using two data, one is using days name on x-axis of chart and second is average temperatures on y-axis. Last line is displaying the chart which is plotted in second line. Now the output of this code will look like –

Output of Line Chart