Python 可视化 - 直方图
Python visualization - histograms
以下两个问题是关于我要构建的直方图的。
1) 我希望分箱如下:
[0-10,10-20,...,580-590, 590-600]。我尝试了以下代码:
bins_range=[]
for i in range(0,610,10):
bins_range.append(i)
plt.hist(df['something'], bins=bins_range, rwidth=0.95)
我希望看到上面的箱子以及每个箱子对应的样本量,但我只得到了 10 个箱子(作为默认参数)。
2) 如何按如下方式更改 y 轴:假设我的 max bin 包含 40 个样本,因此我希望 y 轴上的 40 个样本为 100%,而其他相应。即,30 为 75%,20 为 50%,依此类推。
您的代码似乎运行正常。您甚至可以将 range
命令直接传递给 hist
.
的 bins
参数
要获得百分比形式的 y 轴,我认为您需要两次通过:首先计算 bin 以了解最高 bin 包含多少。然后,使用 1/highest
作为权重进行绘图。有一个 numpy np.hist
可以在不绘图的情况下进行所有计算。
使用 PercentFormatter()
以百分比显示轴。它得到一个参数来告诉有多少 100% 代表。使用 PercentFormatter(max(hist))
得到最高值 100%。如果只希望合计为100%,直接传PercentFormatter(len(x))
即可,不需要计算两次直方图。由于内部 y 轴仍在值中,因此刻度不会显示在所需位置。您可以使用 plt.yticks(np.linspace(0, max(hist), 11))
每 10% 有一个刻度。
为了更好地分离条形,您可以设置明确的边缘颜色。最好没有 rwidth=0.95
示例代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
x = np.random.rayleigh(200, 50000)
hist, bins = np.histogram(x, bins=range(0, 610, 10))
plt.hist(x, bins=bins, ec='white', fc='darkorange')
plt.gca().yaxis.set_major_formatter(PercentFormatter(max(hist)))
plt.yticks(np.linspace(0, max(hist), 11))
plt.show()
PS:要使用 matplotlib 的标准 yticks,并使 y 轴也在内部以百分比表示,您可以使用 hist
的 weights
参数。当您想以交互方式调整绘图大小或缩放绘图,或需要特定百分比的水平线时,这会很方便。
plt.hist(x, bins=bins, ec='white', fc='dodgerblue', weights=np.ones_like(x)/max(hist))
plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
以下两个问题是关于我要构建的直方图的。
1) 我希望分箱如下:
[0-10,10-20,...,580-590, 590-600]。我尝试了以下代码:
bins_range=[]
for i in range(0,610,10):
bins_range.append(i)
plt.hist(df['something'], bins=bins_range, rwidth=0.95)
我希望看到上面的箱子以及每个箱子对应的样本量,但我只得到了 10 个箱子(作为默认参数)。
2) 如何按如下方式更改 y 轴:假设我的 max bin 包含 40 个样本,因此我希望 y 轴上的 40 个样本为 100%,而其他相应。即,30 为 75%,20 为 50%,依此类推。
您的代码似乎运行正常。您甚至可以将 range
命令直接传递给 hist
.
bins
参数
要获得百分比形式的 y 轴,我认为您需要两次通过:首先计算 bin 以了解最高 bin 包含多少。然后,使用 1/highest
作为权重进行绘图。有一个 numpy np.hist
可以在不绘图的情况下进行所有计算。
使用 PercentFormatter()
以百分比显示轴。它得到一个参数来告诉有多少 100% 代表。使用 PercentFormatter(max(hist))
得到最高值 100%。如果只希望合计为100%,直接传PercentFormatter(len(x))
即可,不需要计算两次直方图。由于内部 y 轴仍在值中,因此刻度不会显示在所需位置。您可以使用 plt.yticks(np.linspace(0, max(hist), 11))
每 10% 有一个刻度。
为了更好地分离条形,您可以设置明确的边缘颜色。最好没有 rwidth=0.95
示例代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
x = np.random.rayleigh(200, 50000)
hist, bins = np.histogram(x, bins=range(0, 610, 10))
plt.hist(x, bins=bins, ec='white', fc='darkorange')
plt.gca().yaxis.set_major_formatter(PercentFormatter(max(hist)))
plt.yticks(np.linspace(0, max(hist), 11))
plt.show()
PS:要使用 matplotlib 的标准 yticks,并使 y 轴也在内部以百分比表示,您可以使用 hist
的 weights
参数。当您想以交互方式调整绘图大小或缩放绘图,或需要特定百分比的水平线时,这会很方便。
plt.hist(x, bins=bins, ec='white', fc='dodgerblue', weights=np.ones_like(x)/max(hist))
plt.gca().yaxis.set_major_formatter(PercentFormatter(1))