Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

raise KeyError(key) KeyError: python matplotlib bar chart key error

I have below data frame, on which am creating a chart,

enter image description here

The expectation is to create as below which is in excel,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

But while defining the axis in matplotlib, am facing an issue,

import matplotlib.pyplot as plt
import pandas as pd
import random

def la_bar():
    
    df1 = pd.DataFrame(lst, columns=['source','type','date','count']) #lst is a data set
    ax = df.plot(x="date", y="count", kind="bar")
    df.plot(x="date", y="source", kind="bar", ax=ax)
    plt.savefig("static/images/image.png")
la_bar()

am getting key error as below,

    raise KeyError(key)
KeyError: 'date'

Any suggestion will be appreciated

>Solution :

Use seaborn and barplot with hue parameter:

# pip install seaborn
import pandas as pd
import seaborn as sns
import matplotlib.pyplot

data = {
    'source': ['USA', 'UK', 'Germany'] * 2,
    'type': ['Country'] * 6,
    'date': ['1-Feb-23'] * 3 + ['10-Feb-23'] * 3,
    'count': [2, 1, 4, 3, 1, 2]
}
df = pd.DataFrame(data)

ax = sns.barplot(data=df.sort_values('source'), x='date', y='count', hue='source')
plt.show()

Output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading