在使用 Python 绘制的 histogram/boxplot 的 x 轴上增加 1

Include increments by 1 in the x axis of the histogram/boxplot drawn using Python

我正在尝试在 Python 中绘制一个箱线图,其中 variableAmount 代表 x 轴,Frequency 代表 y 轴,如下面的代码所示:

import matplotlib.pyplot as plt
Frequency = [15097,1207,645,93,68,15,19,10,20,3,4,3,1,1,1,1,1,1,2]
variableAmount = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
'10', '12','13','14', '15', '20', '23', '24', '26', '30'] #sample names

plt.bar(variableAmount, Frequency)
plt.set_xticks(1)
plt.set_yticks(1)

plt.xticks(variableAmount)
plt.yticks(Frequency) #This may be included or excluded as per need
plt.xlabel('Variables per method')
plt.ylabel('Frequency')
plt.show()

我将下面的图作为输出,我遇到的问题是我想在 x 轴上每增加 1 就有一个刻度。正如您在下图中看到的,x 轴上都缺少 9 和 11,我希望每个整数值都包含在 x 轴上,从 0 到 30。

我认为不可能直接在您的情节中执行此操作。但是您可以创建新变量来存储列表的新版本

import matplotlib.pyplot as plt
Frequency = [15097,1207,645,93,68,15,19,10,20,3,4,3,1,1,1,1,1,1,2]
variableAmount = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15, 20, 23, 24, 26, 30] #sample names
New_Frequency = []

for i in range(31):
    if i in variableAmount:
        New_Frequency.append(Frequency[variableAmount.index(i)])
    else:
        New_Frequency.append(0)

variableAmount = [i for i in range(31)]
plt.bar(variableAmount, New_Frequency)

plt.xlabel('Variables per method')
plt.ylabel('Frequency')
plt.show()

你的第一个问题是变量是一个字符串列表。 而且我认为您需要为要显示的 x 定义完整的刻度列表。

你可以用以下方法解决:

import matplotlib.pyplot as plt
Frequency = [15097,1207,645,93,68,15,19,10,20,3,4,3,1,1,1,1,1,1,2]
variableAmount = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
'10', '12','13','14', '15', '20', '23', '24', '26', '30'] #sample names


variableAmount_int=[int(x) for x in variableAmount]
X_ticks_array=[i for i in range(min(variableAmount_int),max(variableAmount_int)+1)]

plt.bar(variableAmount_int, Frequency)
plt.xticks(X_ticks_array)
plt.xlabel('Variables per method')
plt.ylabel('Frequency')
plt.show()

结果: