如何在python中为列表绘制条形图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34029865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to plot bar chart for a list in python
提问by vinay
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 ?
有人可以帮助我将 x 轴作为 a、c、d 和 y 轴值绘制为 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.
我可以绘制条形图,但图表中的 y 轴值是错误的。
回答by 7stud
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:
使用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')
Using plt
methods:
使用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')
回答by user3311110
you are calling numpy but you are not using it
你正在调用 numpy 但你没有使用它
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))