英文:
Histogram of integer values with correct x-axis ticks and labels
问题
以下是您要翻译的代码部分:
import numpy as np
import matplotlib.pyplot as plt
# 生成整数值
n = 20
values = np.random.randint(low=0, high=(n+1), size=1000)
# 绘制直方图
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()
如果您需要进一步的帮助,请随时提出。
英文:
I have integer values from 0
to n
(included) and I would like to plot a histogram with n+1
bars at with the correct x-axis labels. Here is my attempt.
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()
It is almost correct, but the x-axis looks weird.
答案1
得分: 1
这应该可以完成任务。
import numpy as np
import matplotlib.pyplot as plt
# 生成整数值
n = 20
values = np.random.randint(low=0, high=(n+1), size=1000)
# 绘制直方图
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()
英文:
This should do the job.
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论