直方图使用 matplotlib 不可见,并且想在间隔内对 x 轴上的值进行分组

histogram is not visible using matplotlib and would like to group values in the x axis within intervals

我想绘制直方图,但问题是我的直方图不可见。这是我的直方图的样子:

我想在轴内使用以下间隔:[-1,0] ]0,1], ]1,2]]2,4],]4,8],]8,16 ],]16,3​​2]

这是我使用的代码:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

x = ['0',   '1',  '2',   '3', '4',  '5',   '6','7',   '8', '9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','38','40','41','42','43','44','45','48','50','51','53','54','57','60','64','70','77','93','104','108','147'] 
y=  ['164','189','288','444','311','216','122','111','92','54','45','31','31','30','18','15','15','10','4','15','2','8','6','4','7','5','3','3','1','10','3','3','3','2','4','2','1','1','1','2','2','1','1','1','1','1','2','1','2','2','2','1','1','2','1','1','1','1']
x = [int(i) for i in x]
y = [int(i) for i in y]
plt.bar(x, y)
    
plt.xlabel('Variable accesses')
plt.ylabel('Number of Variables')
plt.show()

我该如何解决这个问题?

您可以创建包含区间标签和相应总和的列表:

import matplotlib.pyplot as plt

x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
     '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '38', '40', '41',
     '42', '43', '44', '45', '48', '50', '51', '53', '54', '57', '60', '64', '70', '77', '93', '104', '108', '147']
y = ['164', '189', '288', '444', '311', '216', '122', '111', '92', '54', '45', '31', '31', '30', '18', '15', '15', '10',
     '4', '15', '2', '8', '6', '4', '7', '5', '3', '3', '1', '10', '3', '3', '3', '2', '4', '2', '1', '1', '1', '2',
     '2', '1', '1', '1', '1', '1', '2', '1', '2', '2', '2', '1', '1', '2', '1', '1', '1', '1']
x = [int(xi) for xi in x]
y = [int(yi) for yi in y]
start = -1
end = 0
intervals = []
values = []
while end < 2 * max(x):
    intervals.append(f'$]{start},{end}]$')
    values.append(sum([yi for xi, yi in zip(x, y) if start < xi <= end]))
    start = end
    end = 1 if end == 0 else 2 * end

fig, ax = plt.subplots(figsize=(12, 4))
ax.bar(intervals, values)

ax.set_xlabel('Variable accesses')
ax.set_ylabel('Number of Variables')
ax.margins(x=0.02)
plt.tight_layout()
plt.show()