我的列表看起来像这样
top = [('a',1.875),('c',1.125),('d',0.5)]
有人可以帮我绘制条形图,其中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')
我可以绘制条形图,但图表中的y轴值是错误的.
改变这一行:
import numpy
至:
import numpy as np
改变这一行:
labels, values = zip(*top[])
至:
labels, values = zip(*top)
将这些错误排除在外:
使用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')
使用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')