Python MatPlot柱状图函数参数

8 投票
2 回答
12265 浏览
提问于 2025-04-16 13:05

我正在尝试使用matplot库创建一个柱状图,但我搞不清楚这个函数的参数是什么。

文档上说要用 bar(left, height),但我不知道怎么把我的数据(一个叫x的数字列表)放进去。

当我把高度设置为一个数字,比如 0.51 时,它告诉我高度应该是一个标量;如果我把高度设置为一个列表,它却没有给我错误提示。

2 个回答

2

根据文档内容,您可以在这里找到关于条形图的详细信息:http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.bar

bar(left, height, width=0.8, bottom=0, **kwargs)

其中:

Argument   Description
left   --> the x coordinates of the left sides of the bars
height --> the heights of the bars

这是一个简单的例子,来自于这个网站:http://scienceoss.com/bar-plot-with-custom-axis-labels/

# pylab contains matplotlib plus other goodies.
import pylab as p

#make a new figure
fig = p.figure()

# make a new axis on that figure. Syntax for add_subplot() is
# number of rows of subplots, number of columns, and the
# which subplot. So this says one row, one column, first
# subplot -- the simplest setup you can get.
# See later examples for more.

ax = fig.add_subplot(1,1,1)

# your data here:     
x = [1,2,3]
y = [4,6,3]

# add a bar plot to the axis, ax.
ax.bar(x,y)

# after you're all done with plotting commands, show the plot.
p.show()
4

你可以做一件简单的事情:

plt.bar(range(len(x)), x)

left 是条形图的左边缘。你是在告诉它条形图在横轴上应该放在哪里。这里有一些东西你可以试试,直到你明白为止:

>>> import matplotlib.pyplot as plt
>>> plt.bar(range(10), range(20, 10, -1))
>>> plt.show()

撰写回答