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.

Note1

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 plt.bar() instead of plt.hist().

With plt.bar(), 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 = plt.bar(index, heights, log=logFlag)

Note2

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

http://matplotlib.org/examples/api/barchart_demo.html

Note3

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 = input.next()

#print data

labels = []

newData = []

for i in range(len(data)):

if (data[i] != ”):

newData.append(int(data[i]))

labels.append(i)

csvfile.close();

return newData, labels

def plotHist(filename):

data, labels = readBarChartData(filename)

#print data

fig,ax = plt.subplots()

plt.bar(labels, data)

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

#print titlename

plt.title(titlename)

plt.xlabel(“Dependency Distnace”)

plt.ylabel(“Number of Dependencies”)

#plt.figure()

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

plotHist(sys.argv[1])

 

Advertisements
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:

WordPress.com Logo

You are commenting using your WordPress.com 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