整数值的直方图,带有正确的X轴刻度和标签。

huangapple go评论66阅读模式
英文:

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.

整数值的直方图,带有正确的X轴刻度和标签。

答案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()

huangapple
  • 本文由 发表于 2023年7月12日 23:57:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76672447.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定