Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to plot bar chart for a list in python

My list looks like this

top = [('a',1.875),('c',1.125),('d',0.5)]

Can someone help me plot the bar chart with x-axis as a, c, d and y axis values as 1.875 ,1.125, 0.5 ?

I tried plotting using the following code.

import numpy as np
import matplotlib.pyplot as plt

top = [('a',1.875),('c',1.125),('d',0.5)]

labels, values = zip(*top)
indexes = np.arange(len(labels))
width = 1

plt.bar(indexes, values, width)
plt.xticks(indexes + width * 0.5, labels)
plt.savefig('netscore.png')

I am able plot the bar chart but y-axis values are wrong in the chart.

like image 257
vinay Avatar asked Dec 01 '15 20:12

vinay


1 Answers

Change this line:

import numpy

to:

import numpy as np

Change this line:

labels, values = zip(*top[])

to:

labels, values = zip(*top)

With those errors out of the way:

Using axes methods:

import numpy as np                                                               
import matplotlib.pyplot as plt  

top=[('a',1.875),('c',1.125),('d',0.5)]

labels, ys = zip(*top)
xs = np.arange(len(labels)) 
width = 1

fig = plt.figure()                                                               
ax = fig.gca()  #get current axes
ax.bar(xs, ys, width, align='center')

#Remove the default x-axis tick numbers and  
#use tick numbers of your own choosing:
ax.set_xticks(xs)
#Replace the tick numbers with strings:
ax.set_xticklabels(labels)
#Remove the default y-axis tick numbers and  
#use tick numbers of your own choosing:
ax.set_yticks(ys)

plt.savefig('netscore.png')

Using plt methods:

import numpy as np                                                               
import matplotlib.pyplot as plt

top=[('a',1.875),('c',1.125),('d',0.5)]

labels, ys = zip(*top)
xs = np.arange(len(labels)) 
width = 1

plt.bar(xs, ys, width, align='center')

plt.xticks(xs, labels) #Replace default x-ticks with xs, then replace xs with labels
plt.yticks(ys)

plt.savefig('netscore.png')

enter image description here

like image 106
7stud Avatar answered Sep 25 '22 20:09

7stud