我正在使用 matplotlib 生成直方图。
我需要垃圾箱的宽度不等,因为我最感兴趣的是最低的垃圾箱。现在我正在这样做:
plt.hist(hits_array, bins = (range(0,50,10) + range(50,550,50)))
Run Code Online (Sandbox Code Playgroud)
这创建了我想要的(前 5 个 bin 的宽度为 10,其余为 50),但是前 5 个 bin 显然比后面的窄,因为所有 bin 都显示在同一轴上。
有没有办法影响 x 轴或直方图本身,以便我可以在前 5 个 bin 之后打破比例,以便所有 bin 显示为同等宽度?
(我意识到这会产生扭曲的视图,我对此很满意,尽管我不介意轴的两个不同比例的部分之间有一点空间。)
任何帮助将不胜感激。谢谢!
我在这里有一个类似的问题,答案是使用肮脏的黑客。 Matplotlib 直方图,带有高值收集箱
因此,通过以下代码,您将得到已有的丑陋的直方图。
def plot_histogram_04():
limit1, limit2 = 50, 550
binwidth1, binwidth2 = 10, 50
data = np.hstack((np.random.rand(1000) * limit1, np.random.rand(100) * limit2))
bins = range(0, limit1, binwidth1) + range(limit1, limit2, binwidth2)
plt.subplots(1, 1)
plt.hist(data, bins=bins)
plt.savefig('my_plot_04.png')
plt.close()
Run Code Online (Sandbox Code Playgroud)

为了使垃圾箱等宽,您确实必须使它们等宽!这意味着操作您的数据,使它们全部落入宽度相等的容器中,然后使用 xlabel。
def plot_histogram_05():
limit1, limit2 = 50, 550
binwidth1, binwidth2 = 10, 50
data = np.hstack((np.random.rand(1000) * limit1, np.random.rand(100) * limit2))
orig_bins = range(0, limit1, binwidth1) + range(limit1, limit2 + binwidth2, binwidth2)
data = [(i - limit1) / (binwidth2 / binwidth1) + limit1
if i >= limit1 else i for i in data]
bins = range(0, limit2 / (binwidth2 / binwidth1) + limit1, binwidth1)
_, ax = plt.subplots(1, 1)
plt.hist(data, bins=bins)
xlabels = np.array(orig_bins, dtype='|S3')
N_labels = len(xlabels)
print xlabels
print bins
plt.xlim([0, bins[-1]])
plt.xticks(binwidth1 * np.arange(N_labels))
ax.set_xticklabels(xlabels)
plt.savefig('my_plot_05.png')
plt.close()
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
23586 次 |
| 最近记录: |