【问题标题】:allow duplicates within x axis of a histogram in Python允许在 Python 中直方图的 x 轴内重复
【发布时间】:2020-11-29 00:42:21
【问题描述】:

我想绘制一个以频率为 x 轴和 variableAmount 为 y 轴的直方图,我还想在 x 轴内允许重复值。如您所见,我正在使用以下代码,它不允许在 x 轴内重复值:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

variableAmount = [16,20,21,10,12,25,9,13,7,6,5,8,4,3,2,1,0]
Frequency = ['1','1','1','2','2','2','4','4','7','11','12','13','62','105','464','1726','14775'] #sample names


plt.bar(Frequency, variableAmount)
plt.xlabel('Number of Methods')
plt.ylabel('Variables')
plt.show()

这是我获得的结果图,如您所见,2、4 和 1 在直方图的 x 轴内仅出现一次,这是错误的,因为 1 出现 3 次,2 出现 3 次,4 出现 2 次在我的代码中指定的频率数组中(['1','1','1','2','2','2','4','4'...])。如何解决此问题并在直方图的 x 轴内允许重复值?

【问题讨论】:

    标签: python matplotlib duplicates histogram


    【解决方案1】:

    它们都被绘制了,但一些较小的条被较大的条覆盖,因为有些条被绘制在同一位置。也许绕路会有所帮助?

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    
    variableAmount = [16,20,21,10,12,25,9,13,7,6,5,8,4,3,2,1,0]
    Frequency = ['1','1','1','2','2','2','4','4','7','11','12','13','62','105','464','1726','14775'] #sample names
    helper = np.arange(len(Frequency))
    
    plt.bar(helper, variableAmount)
    plt.xticks(ticks=helper, labels=Frequency, rotation=45)
    
    plt.xlabel('Number of Methods')
    plt.ylabel('Variables')
    plt.show()
    

    示例输出:

    但是1 有多个值是什么意思?我不知道。

    【讨论】:

    • 它不起作用:AttributeError: Unknown property ticks
    • Why would that be? 您可以省略关键字,但您的 matplotlib 版本抱怨它是没有意义的。除非您运行 3.1 之前的 matplotlib 版本。在这种情况下,您应该在问题中指定您使用的版本。
    • 我在 Spyder 3.3.1 上使用 Python 3.7
    • matplotlib: 2.2.3
    • 我建议你把这个放到问题中。我们现在是 3.3.3。要么更新你的 matplotlib,要么等待仍然使用这个过时版本的人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2017-04-21
    • 2020-04-02
    相关资源
    最近更新 更多