Search code examples
pythonpandasplotstacked-chart

Pandas: Stacked bar chart of a column of dictionaries of key and values


I have a pandas dataframe as follows but with more rows:

>>> import pandas as pd

>>> data = {'First':  ['First value', 'Second value'],
'Second': [{'NOUN': 13, 'VERB': 8, 'PRON': 3}, {'PROPN': 2, 'VERB': 10, 'NOUN': 11}],}

>>> df = pd.DataFrame (data, columns = ['First','Second'])

I would like to plot the values using a stacked bar chart. I am new to python, so I am not sure how I can do that with a dictionary.


Solution

  • I would import the dictionary differently:

    import pandas as pd
    from matplotlib import pyplot as plt
    
    data = {'First':  ['First value', 'Second value'],
    'Second': [{'NOUN': 13, 'VERB': 8, 'PRON': 3}, {'PROPN': 2, 'VERB': 10, 'NOUN': 11}],}
    
    df = pd.DataFrame(data["Second"], index=data["First"])
    df.plot(kind="bar", stacked="True")
    
    plt.tight_layout()
    plt.show()
    

    Sample output:

    enter image description here