[Python] Can't get frequency data right for Seaborn histogram

Discussão em 'Python' iniciado por Stack, Junho 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have a list containing thousands of survey answers ranging from 'A' to 'I', with the addition of None for blanks:

    Raw data list example:

    [None, 'A', 'G', None, None, 'I', 'B', ...<snip>... , 'C']


    I would like to produce a Seaborn histogram showing the frequency of each response (in alphabetical order), something similar to this Excel chart:

    Desired outcome (Excel version)

    Desired outcome (Numbers are different here than in test data below)

    The closest I get is this, with all columns incorrectly equal to 1:

    Histogram with correct axes but wrong column heights

    I tried histplot, catplot and displot as per some random tutorials online.

    I am unsure of how to process the list of raw values into the right format for Seaborn. I have followed many different tutorials doing things like sns.histplot(data=df, x="Frequency") but can't get the dataframe right before this step.

    Main method I tried for frequency (from some tutorials): df = pd.DataFrame.from_dict(Counter(values), orient='index').reset_index()

    Any suggestions will be humbly received.

    Much appreciation in advance.

    Minimum reproducible example:

    import matplotlib.pyplot as plt
    from collections import Counter
    import seaborn as sns
    import pandas as pd


    # Test data - real data is much larger and extracted as a list from an SQLite3 DB.
    values = ['E', None, 'B', 'H', 'I', 'A', None, None, 'D',
    'C', 'E', 'I', 'C', 'B', None, 'A', None, 'E',
    'F', 'H', 'A', 'D', 'A', 'A', 'F', 'A', 'C',
    'C', 'H', 'E', None, 'B', 'E', 'I', 'G', 'A',
    'I', 'A', 'B', 'I']

    sns.set_theme(style="darkgrid")
    df = pd.DataFrame.from_dict(Counter(values), orient='index').reset_index()
    df.columns = ['Choice', 'Frequency']
    sns.histplot(data=df, x='Choice')
    plt.show()

    Continue reading...

Compartilhe esta Página