python-3.xdateplotagainst

How to plot categorical variable against a date column in Python


I have data that looks like this

Date         Fruit
2017-01-01   Orange
2017-01-01   Apple
2017-01-08   Orange
2017-01-09   Orange
2017-01-09   Apple

I want to plot Number of Oranges, Number of Apples by Date in a single plot. How would I do that?

I grouped them by Date and I see the result.

df.groupby(['Date','Fruit']).size()
Date         Fruit
2017-01-01   Orange  1
             Apple   1
2017-01-08   Orange  1
2017-01-09   Orange  1
             Apple   1

I tried this but it gives a bar plot having two categories but not against the dates.

sns.catplot(x="Fruit", hue="Fruit", kind="count",
            palette="pastel", edgecolor=".6",
            data=df);

How can plot a graph have Date on the x-axis and number of apples and the number of oranges for each date?


Solution

  • Framing the dataset:

    df = pd.DataFrame(columns=["Date", "Fruit"], data=[['2017-01-01','Orange'], ['2017-01-01','Orange'], ['2017-01-01','Apple'], ['2017-01-08','Orange'], ['2017-01-09','Orange'], ['2017-01-09','Apple']])
    

    The data looks like this

    By using unstack and group by a bar plot can be drawn:

    (df
     .groupby(['Date', 'Fruit'])
     .size()
     .unstack()
     .plot.bar()
    )
    

    Here is the plot by date