Reputation: 81
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.
Upvotes: 8
Views: 44313
Reputation: 48649
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')
Upvotes: 11
Reputation: 46
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))
Upvotes: 0