1

I am trying to plot some data from pandas. First I group by weeks and count for each grouped week, them I want to plot for each date, however when I try to plot I get just some dates, not all of them.

I am using the following code:

my_data = res1.groupby(pd.Grouper(key='d', freq='W-MON')).agg('count').u
p1,  = plt.plot(my_data, '.-')
a = plt.xticks(rotation=45)

My result is the following:

enter image description here

I wanted a value in the x-axis for each date in the grouped dataframe.

EDIT: I tried to use plt.xticks(list(my_data.index.astype(str)), rotation=45) The plot I get is the following: I would like to have the complete dates

3
  • you can simply put the list of dates you want to display for each point in plt.xticks(dates) Commented Oct 9, 2018 at 8:37
  • I tried doing that, however instead of having the whole dates I get just the year Commented Oct 9, 2018 at 8:40
  • You would benefit from creating a minimal reproducible example of the issue, such that people can give an answer which actually suits your needs. Commented Oct 9, 2018 at 9:21

1 Answer 1

1

Please find a working chunk of code below:

from datetime import date, timedelta
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np

a = pd.Series(np.random.randint(10, 99, 10))

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())

plt.plot(pd.date_range(date(2016,1,1), periods=10, freq='D'), a)
plt.gcf().autofmt_xdate()

enter image description here

Hope it helps :)

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

4 Comments

If you generate the data with freq='D', using a DayLocator is reasonable for ticking each date that occurs in the data. What if the frequency is different? This is what the question asks about as I understand it.
i wasn't able to make this work, however plt.xticks(list(my_data.index.astype(str)), list(my_data.index.astype(str)), rotation=45) worked for me
@ImportanceOfBeingErnest valid point, depending upon the frequency DayLocator, MonthLocator, YearLocator etc had to be used.
@JorgeRodriguezMolinuevo: your way is must succinct, indeed

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.