python - 在Python中绘制条形图

标签 python numpy matplotlib

我是 Python 编程新手。我正在学习Python。

下面的代码帮助我绘制了条形图。我正在尝试理解代码。 我无法理解第 5、6、7 和 8 行。即,

N = len(data)
x = np.arange(1,N+1)
y = [num for (s, num) in data ]
labels = [ s for (s, num) in data ]

此外,为什么我们在绘制 x 轴标签时采用 x+width/2.0 ? 并且,如何在房屋盗窃之前在图表的开头设置较小的宽度?条形通常从 0 开始。我不知道如何在第一个条形开始之前设置一个小宽度。我尝试过,但无法正常运行。

完整的程序如下。

import matplotlib.pyplot as plt
import numpy as np
data = [ ("House Theft", 57), ("House Fire", 48),
            ("Car Theft", 156), ( "Car Accident", 245)]
N = len(data)
x = np.arange(1,N+1)
y = [num for (s, num) in data ]
labels = [ s for (s, num) in data ]
width = 0.35 #Use 1 to make it as a histogram
bar1 = plt.bar( x, y, width, color="y")
plt.ylabel( 'Frequency' )
plt.xticks(x + width/2.0, labels )
plt.show()

最佳答案

Multiple assignment, tuple/sequence packing/unpacking :

>>> 
>>> data = [ ("House Theft", 57), ("House Fire", 48),
            ("Car Theft", 156), ( "Car Accident", 245)]
>>> 
>>> for thing in data:
    (s, num) = thing
    print thing, '\t', s, '\t', num

('House Theft', 57)     House Theft     57
('House Fire', 48)      House Fire      48
('Car Theft', 156)      Car Theft       156
('Car Accident', 245)   Car Accident    245
>>>
<小时/>
>>> for (s, num) in data:
    print s, '\t\t', num


House Theft         57
House Fire          48
Car Theft           156
Car Accident        245
>>>
<小时/>

plt.xticks(x + width/2.0, labels ) 会将 x 轴上的刻度偏移宽度的一半。不知道为什么这样做,除了视​​觉效果。

>>> x = np.arange(1,11)
>>> x
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
>>> width = .5
>>> x + width/2
array([  1.25,   2.25,   3.25,   4.25,   5.25,   6.25,   7.25,   8.25,   9.25,  10.25])
>>> 

关于python - 在Python中绘制条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32425045/

相关文章:

python - 为什么这些 numpy 操作不等效,我该如何解决这个问题?

python - 具有约 2000 万个样本点和千兆字节数据的交互式大图

python - 如何告诉 PyCharm async fixture 返回了一些东西

python - 类型错误 : 'TextBlob' object is not callable

python - Geopandas 数据框到 GeoJSON 到 Elasticsearch 索引?

带有请求的 Python 网络抓取 - 在响应中只得到一小部分数据

python - 使用 Python 在 OpenCV 中删除图像

python - 如何在numpy中找到已编译的扩展模块

python - 绘制给定均值和西格玛的正态分布 - python

Python matplotlib x 轴值