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

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

Histogram of integer values with correct x-axis ticks and labels

问题

以下是您要翻译的代码部分:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # 生成整数值
  4. n = 20
  5. values = np.random.randint(low=0, high=(n+1), size=1000)
  6. # 绘制直方图
  7. fig, ax = plt.subplots(figsize=(20, 4))
  8. _, bins, _ = ax.hist(values, bins=n+1, edgecolor='k', color='lightsalmon')
  9. ax.set_xticks(bins)
  10. ax.set_xticklabels(bins.astype(int))
  11. 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.

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Generate integer values
  4. n = 20
  5. values = np.random.randint(low=0, high=(n+1), size=1000)
  6. # Plot histogram
  7. fig, ax = plt.subplots(figsize=(20, 4))
  8. _, bins, _ = ax.hist(values, bins=n+1, edgecolor='k', color='lightsalmon')
  9. ax.set_xticks(bins)
  10. ax.set_xticklabels(bins.astype(int))
  11. plt.show()

It is almost correct, but the x-axis looks weird.

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

答案1

得分: 1

这应该可以完成任务。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # 生成整数值
  4. n = 20
  5. values = np.random.randint(low=0, high=(n+1), size=1000)
  6. # 绘制直方图
  7. fig, ax = plt.subplots(figsize=(20, 4))
  8. bins = np.arange(start=-0.5, stop=(n+1), step=1)
  9. _ = ax.hist(values, bins=bins, edgecolor='k', color='lightsalmon')
  10. ax.set_xticks(np.arange(n+1))
  11. plt.show()
英文:

This should do the job.

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Generate integer values
  4. n = 20
  5. values = np.random.randint(low=0, high=(n+1), size=1000)
  6. # Plot histogram
  7. fig, ax = plt.subplots(figsize=(20, 4))
  8. bins = np.arange(start=-0.5, stop=(n+1), step=1)
  9. _ = ax.hist(values, bins=bins, edgecolor='k', color='lightsalmon')
  10. ax.set_xticks(np.arange(n+1)
  11. 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:

确定