1

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'

What can I try to resolve this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Jim Macaulay
  • 4,709
  • 4
  • 28
  • 53

1 Answers1

1

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

Corralien
  • 109,409
  • 8
  • 28
  • 52