8

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.

1
  • After fixing the syntax errors the code works like a charm on my system. Histogram looks fine. Commented Dec 1, 2015 at 21:03

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

Comments

0

you are calling numpy but you are not using it

on the line

indexes = np.arange(len(labels))

i guess you were trying to use it, either do:

import numpy as np

or:

indexes = numpy.arange(len(labels))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.