首页 > 解决方案 > 使用不同的 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()

在此处输入图像描述

标签: matplotlib

解决方案


问题是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()

bar_plot_integers


推荐阅读