如何在python中为数组绘制直方图?

2024-04-27 10:58:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数组,它有不同的值,其中一些是重复的。如何为横轴为元素名称,纵轴为数组中的数字的元素绘制直方图

arr= ['a','a','a','b','c','b']

Tags: 名称元素绘制数字数组直方图横轴arr
3条回答

解决此问题有多个步骤

步骤1: 您需要在方便的位置收集数据。根据您的示例,一个好的选择是列出一个包含值的列表。这可以使用.count()来实现。当然,其他方法也是可能的

步骤2: 要显示数据,可以使用类似matplotlib.pyplot的库。这也可能涉及步骤1。但这并不重要

如果您的用例不同。请提供更多详细信息,以便我们能更好地帮助您

请注意,matplotlib的^{}不能很好地处理字符串数据(请参见条形图/勾选位置):

import matplotlib.pyplot as plt

plt.hist(arr)

当然可以手动修复这个问题,但使用熊猫或海洋生物更容易。两者都在后台使用matplotlib,但它们提供了更好的默认格式

此外:

  • 如果有太多的条不能很好地适应默认帧,可以加宽figsize。在这些示例中,我设置了figsize=(6, 3)
  • 如果要旋转x刻度,请添加plt.xticks(rotation=90)

熊猫

  • 熊猫^{}^{}

    import pandas as pd
    
    pd.value_counts(arr).plot.bar(figsize=(6, 3))
    # pd.Series(arr).value_counts().plot.bar(figsize=(6, 3))
    


seaborn

  • seaborn ^{}

    import seaborn as sns
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(figsize=(6, 3))
    sns.histplot(arr, ax=ax)
    

  • seaborn ^{}

    import seaborn as sns
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(figsize=(6, 3))
    sns.countplot(arr, ax=ax)
    


matplotlib

  • ^{}带matplotlib^{}

    from collections import Counter
    
    counts = Counter(arr)
    fig, ax = plt.subplots(figsize=(6, 3))
    ax.bar(counts.keys(), counts.values())
    

  • numpy^{}与matplotlib^{}

    import numpy as np
    
    uniques, counts = np.unique(arr, return_counts=True)
    fig, ax = plt.subplots(figsize=(6, 3))
    ax.bar(uniques, counts)
    

您可以使用matplotlib库直接从列表中绘制直方图。其代码如下所示:

from matplotlib import pyplot as plt

arr= ['a','a','a','b','c','b']

plt.hist(arr)
plt.show()

您可以在matplotlib中查看有关直方图函数的更多信息:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hist.html

你可以做其他的事情,比如设置直方图的颜色,改变对齐方式,还有很多其他的事情

干杯

相关问题 更多 >