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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With