matplotlib - 使用不同的 x 轴 Python 绘制图形
问题描述
我试图从模拟和在同一张图中观察到的一些不同的分布。这些线代表模拟的分布并且具有从 1 到 9 的值,它们是遵循本福德定律的样本。
而作为观察分布的条形图有一些缺失值 (3,4,5,6),这些值来自变量 中所有元素的第一个数字amount
。我的最终图表看起来很奇怪。当我绘制条形图时,有人可以解释如何保留这些缺失值吗?非常感谢你。
amount=np.array([1927.46, 27902.31, 86241.90, 72117.46, 81321.75, 97473.96, 93249.11, 89658.17, 87776.89, 92105.83, 79949.16, 87602.93, 96879.27, 91806.47, 84991.67, 90831.83, 93776.67, 88336.72, 94639.69, 83709.28, 96412.21, 88432.86, 71552.15])
np.random.seed(1000)
for i in range(10):
u = np.random.rand(23)
samples = np.floor(10**u)
values,counts = np.unique(np.array(samples),return_counts=True)
plt.plot(values,counts/np.sum(counts),color="blue",label="sample",marker="o",zorder=2)
amount = amount.astype("str")
first = [d[0] for d in amount]
values,counts = np.unique(np.array(first),return_counts=True)
plt.bar(values,counts/np.sum(counts),label="observed")
plt.show()
解决方案
问题是values
对于条形图存储为字符串。Matplotlib 像任何其他字符串一样绘制这些字符串,将它们并排放置在 x 轴上,从位置 0 开始直到位置 4 的最后一个字符串(数字 9 的条形图)。print(plt.xticks())
您可以通过在之前添加到您的代码来验证这一点plt.show()
。
要解决此问题,您必须使用整数数组。在以下示例中,这是通过更改 的数据类型来完成的first
。此外,对刻度进行编辑以显示值范围内每个整数的刻度标签:
import numpy as np # v 1.19.2
import matplotlib.pyplot as plt # v 3.3.2
amount=np.array([1927.46, 27902.31, 86241.90, 72117.46, 81321.75, 97473.96, 93249.11,
89658.17, 87776.89, 92105.83, 79949.16, 87602.93, 96879.27, 91806.47,
84991.67, 90831.83, 93776.67, 88336.72, 94639.69, 83709.28, 96412.21,
88432.86, 71552.15])
np.random.seed(1000)
for i in range(10):
u = np.random.rand(23)
samples = np.floor(10**u)
values,counts = np.unique(np.array(samples),return_counts=True)
plt.plot(values,counts/np.sum(counts),color="blue",label="sample",marker="o",zorder=2)
amount = amount.astype("str")
first = np.array([d[0] for d in amount]).astype(int)
values,counts = np.unique(first, return_counts=True)
plt.bar(values,counts/np.sum(counts),label="observed")
plt.xticks(range(min(values), max(values)+1))
plt.show()
推荐阅读
- c# - 在空闲事件上重复播放视频并在检测到用户活动时恢复到上一个窗口
- google-bigquery - BigQuery - 联合上的相关子查询不起作用
- actions-on-google - 如何更新你的谷歌助手琐事问题
- c++ - 访问结构向量
- liferay - 更新 Liferay-faces-alloy
- sql - SQL - 在脚本中处理 IS NULL
- java - 静态内部类可以扩展其外部类吗?
- spring-boot - 使用 jdbc 模板在 api 中关闭连接
- twitter-bootstrap - 使用引导程序内联两个元素
- javascript - 需要视频在按键时静音/取消静音(无按钮)