当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何在python中绘制列表的条形图》经验,为你挑选了1个好方法。

我的列表看起来像这样

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轴值是错误的.



1> 7stud..:

改变这一行:

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')

在此输入图像描述

推荐阅读
无名有名我无名_593
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有