numpy 具有正确x轴刻度和标签的整数值直方图

icnyk63a  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(69)

我有从0n(包括在内)的整数值,我想用正确的x轴标签绘制一个n+1条形图。这是我的尝试。

import numpy as np
import matplotlib.pyplot as plt

# Generate integer values
n = 20
values = np.random.randint(low=0, high=(n+1), size=1000)

# Plot histogram
fig, ax = plt.subplots(figsize=(20, 4))
_, bins, _ = ax.hist(values, bins=n+1, edgecolor='k', color='lightsalmon')
ax.set_xticks(bins)
ax.set_xticklabels(bins.astype(int))
plt.show()

字符串
这几乎是正确的,但x轴看起来很奇怪。


的数据

798qvoo8

798qvoo81#

这个应该可以了

import numpy as np
import matplotlib.pyplot as plt

# Generate integer values
n = 20
values = np.random.randint(low=0, high=(n+1), size=1000)

# Plot histogram
fig, ax = plt.subplots(figsize=(20, 4))
bins = np.arange(start=-0.5, stop=(n+1), step=1)
_ = ax.hist(values, bins=bins, edgecolor='k', color='lightsalmon')
ax.set_xticks(np.arange(n+1)
plt.show()

字符串

相关问题