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

Question:

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,

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

Asked By: Jim Macaulay

||

Answers:

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

Answered By: Corralien
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.