I have below data frame, on which am creating a chart,
The expectation is to create as below which is in excel,
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: