How to draw a bar chart (histogram) in Python

This is a summary of the things I learned from trying to draw a bar chart in Python. I use the barchart to create a histogram for large scale of data, when fitting all of the data in a data array in histogram API is not possible.


The histogram function draws a histogram out of all the data points. This is NOT what you want if you already have the data of occurences in csv file. In this case, you actually want to use instead of plt.hist().

With, you have better control over what the xaxis and yaxis is going to look like.

An example line of how to use bar charts

rects1 =, heights, log=logFlag)


The best link for a tutorial, no doubt is the following


To make your plot title wrap around,

fig,ax = plt.subplots()

figtitle = ax.set_title(“\n”.join(wrap(title, 60)))


Some example code are shown here that starts with reading csv to generate the barchartrs

import sys

import csv

import matplotlib.pyplot as plt

import os

import numpy as np

from textwrap import wrap

def readBarChartData(filename):

csvfile = open(filename, ‘rb’)

input = csv.reader(csvfile)

data =

#print data

labels = []

newData = []

for i in range(len(data)):

if (data[i] != ”):




return newData, labels

def plotHist(filename):

data, labels = readBarChartData(filename)

#print data

fig,ax = plt.subplots(), data)

titlename = filename.split(‘.’)[0]

#print titlename


plt.xlabel(“Dependency Distnace”)

plt.ylabel(“Number of Dependencies”)


plt.savefig(‘./png/’ + filename + ‘.png’)



This entry was posted in Tools and tagged . Bookmark the permalink.

One Response to How to draw a bar chart (histogram) in Python

  1. Hello everyone, it’s my first pay a quick visit at this web site, and article is
    actually fruitful in favor of me, keep up posting such posts.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s