如何在python中绘制列表的条形图

vin*_*nay 6 python matplotlib

我的列表看起来像这样

top = [('a',1.875),('c',1.125),('d',0.5)]
Run Code Online (Sandbox Code Playgroud)

有人可以帮我绘制条形图,其中x轴为a,c,d和y轴值为1.875,1.125,0.5?

我尝试使用以下代码进行绘图.

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')
Run Code Online (Sandbox Code Playgroud)

我可以绘制条形图,但图表中的y轴值是错误的.

7st*_*tud 10

改变这一行:

import numpy
Run Code Online (Sandbox Code Playgroud)

至:

import numpy as np
Run Code Online (Sandbox Code Playgroud)

改变这一行:

labels, values = zip(*top[])
Run Code Online (Sandbox Code Playgroud)

至:

labels, values = zip(*top)
Run Code Online (Sandbox Code Playgroud)

将这些错误排除在外:

使用axes方法:

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')
Run Code Online (Sandbox Code Playgroud)

使用plt方法:

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')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述