0

I'm trying to change my date time format to dd-mm or mm-dd but I'm not sure how to do it. I've looked at other stack overflow questions and answers but I think I may have done my plot a little differently to them as I am computing the sum for each of the different days.

data = {'date': ['2020-09-01', '2020-09-02', '2020-09-03', '2020-09-04', '2020-09-01'],
    'newcases': [1, 2, 4, 7, 10]}

df = pd.DataFrame(data, columns = ['date','newcases'])

df['date'] = pd.to_datetime(df['date']) #converted to datetime

import matplotlib.dates as mdates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m'))
df.groupby('date').newcases.sum().plot(kind = 'bar')

This is what I have tried but I am not able to format the x-ticks into the right format (dd-mm). It still looks like this:

enter image description here

2
  • What did you try? Can you provide a minimal reproducible example? (as text/code ideally, not screenshot) Commented Dec 25, 2020 at 20:29
  • 1
    I've just changed the original question to a sample data frame. Any help you can offer will be much appreciated! I'm trying to learn Python and have taken a sample COVID-19 dataset to practice on :) Commented Dec 25, 2020 at 21:39

1 Answer 1

1

Pandas creates a new figure/axes when plotting (unless you pass an axes object to it). So you need to first plot and then change the axis formatter of the plot you just now created (gca = get current axes), i.e. just change the order of your last two lines of code:

df.groupby('date').newcases.sum().plot(kind = 'bar')
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m'))

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, I've tried this previously but I get an error. The error is 'DateFormatter found a value of x=0, which is an illegal date; this usually occurs because you have not informed the axis that it is plotting dates, e.g., with ax.xaxis_date()'
What Pandas version are you using? Your example works perfectly with the changed order for pandas 1.1.3 and matplotlib 3.3.0, see attached picture in the answer.
for older versions of pandas you could use df.groupby(df['date'].dt.strftime('%d-%m')).newcases.sum().plot(kind = 'bar')
Ah thank you so much, I've just updated my Anaconda Navigator and it works now. I didn't realise it may have been that I was using a much older version of Anaconda!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.