Numpy 直方图表达式
Numpy Histogram expression
请考虑局部变量few_counts
。
import numpy as np
import matplotlib.pyplot as plt
few_rolls = np.random.randint(1,7,size=10)
few_counts = np.histogram(few_rolls, bins=np.arange(0.5, 7.5))[0]
我不明白为什么直方图表达式外的方括号中必须有一个 0 才能使代码正确 运行。如果我删除它或更改值,代码将失败,如下所示:
# Remove [0]
few_counts = np.histogram(few_rolls, bins=np.arange(0.5, 7.5))
# Create figure and axes
fig, (ax1, ax2) = plt.subplots(1,2,figsize=(8,3))
# Code fails here
ax1.bar(np.arange(1,7), few_counts)
有人可以解释为什么有必要在直方图函数之外添加 [0]
吗?
根据 documentation、numpy.histogram
returns hist
和 bin_edges
。 hist
是直方图的值,bin_edges
是 x 轴上条形的边缘。
通过在 numpy.histogram(...)
末尾添加 [0]
,您将选择函数返回的第一个数组。因此,您选择的是 hist
数组。如果不这样做,您会将两个数组作为 height
传递给 ax1.bar()
(即您会将 hist
和 bin_edges
作为 height
传递) .
请考虑局部变量few_counts
。
import numpy as np
import matplotlib.pyplot as plt
few_rolls = np.random.randint(1,7,size=10)
few_counts = np.histogram(few_rolls, bins=np.arange(0.5, 7.5))[0]
我不明白为什么直方图表达式外的方括号中必须有一个 0 才能使代码正确 运行。如果我删除它或更改值,代码将失败,如下所示:
# Remove [0]
few_counts = np.histogram(few_rolls, bins=np.arange(0.5, 7.5))
# Create figure and axes
fig, (ax1, ax2) = plt.subplots(1,2,figsize=(8,3))
# Code fails here
ax1.bar(np.arange(1,7), few_counts)
有人可以解释为什么有必要在直方图函数之外添加 [0]
吗?
根据 documentation、numpy.histogram
returns hist
和 bin_edges
。 hist
是直方图的值,bin_edges
是 x 轴上条形的边缘。
通过在 numpy.histogram(...)
末尾添加 [0]
,您将选择函数返回的第一个数组。因此,您选择的是 hist
数组。如果不这样做,您会将两个数组作为 height
传递给 ax1.bar()
(即您会将 hist
和 bin_edges
作为 height
传递) .