Plotting Graphs

Hi,
This is my code:

covid_cases_uk_df.cases.plot(figsize=(20, 5), title=‘Covid UK Cases’);

How can I make the months appear on x axis instead of dates. See image below.
Thanks.

You need to group this by month.

Apparently, pandas provide a Grouper class that can group the dataframe by date with a given frequency:

df.groupby(pd.Grouper(key='date_column_name', freq='1M')).mean()

You can then use this new dataframe to plot data by month.

1 Like

I tried this -
covid_cases_uk_df.groupby(pd.Grouper(key=“date”, freq=“1M”)).mean()

covid_cases_uk_df.cases.plot(figsize=(20, 5), title=‘Covid UK Cases’);

Still doesn’t work

You’re using the old variable still.

You need to assign somewhere the result of groupby method.

df_by_month = blabla.groupby...

Then you should plot this new result.

Thanks. Creating a new variable worked.

Hi,
One more question .
Is there a way to plot real case numbers rather than a mean numbers on Y axis.?

If you group by month and then aggregate with mean you’ll get mean of the cases over a whole month.

What kind of “real case numbers” do you want?

If you aim for the look from first graph (which is kinda wrong, because you haven’t prepared the data), but change the x axis labels, you can add a column to dataframe that represents the month in which given value has been recorded and then use this dataframe to plot the graph (without grouping) by setting this new column as an index.

@rl2000 use plotly library to plot the cases day wise, it is interactive too. In this you dont have to take mean of cases moth wise.

1 Like