1

I have two lists: one is dates and othe is data.

alldates =    Index(['2019-01-25', '2019-01-26', ...'2019-05-09'], dtype='object')
data = [0.9868203770867318, .... ,0.9257586144368741]

I want to plot them. My code and result is:

plt.plot(alldates,data,'-*',label='R$^2$ score')
plt.locator_params(axis='x', nbins=5)
plt.ylim([-1,1.2])
plt.legend(loc='best')
plt.show()

Plot is:

enter image description here

Also it was giving some error message:

    C:\Users\MMatam\Anaconda3\lib\site-packages\matplotlib\ticker.py:
    1437: UserWarning: 'set_params()' not defined for locator 
of type <class 'matplotlib.category.StrCategoryLocator'>
          str(type(self)))

Did you see the x-axis ticks? Looks like my plt.locator_params(axis='x', nbins=5) did not work. How to get only few ticks on this axis?

Msquare
  • 775
  • 7
  • 17
  • @Vishnudev please dont quote this a duplicate without reading the question properly. I have already gone through the solution you have quoted but it is not same. – Msquare Jun 03 '19 at 17:12
  • 1
    Try to change `alldates` into `datetime` type, not string. – Quang Hoang Jun 03 '19 at 17:13
  • @QuangHoang, I am new to python. Don't mind, how to change it? – Msquare Jun 03 '19 at 17:14
  • You are not providing enough information, since I'm not sure what `alldates = Index(['2019-01-25', '2019-01-26', ...'2019-05-09'], dtype='object')` means. Does it come from a `pd` dataframe? – Quang Hoang Jun 03 '19 at 17:16
  • @QuangHoang it is just a list. – Msquare Jun 03 '19 at 17:16
  • What's `Index`? – Quang Hoang Jun 03 '19 at 17:17
  • @QuangHoang I get this output when I do `print(alldates)` – Msquare Jun 03 '19 at 17:20
  • https://matplotlib.org/3.1.0/gallery/ticks_and_spines/tick-locators.html – iamchoosinganame Jun 03 '19 at 17:21
  • Then `alldates` is not just a list. `print(alldates)` is not equivalent to what it is. You should edit your question and include your **definition** of `alldates`. – Quang Hoang Jun 03 '19 at 17:21
  • The second comment is correct. Add `alldates = pd.to_datetime(alldates)` before plotting. Also see [this](https://stackoverflow.com/questions/9627686/plotting-dates-on-the-x-axis-with-pythons-matplotlib) and [this](https://stackoverflow.com/questions/49418248/plot-x-axis-as-date-in-matplotlib). – ImportanceOfBeingErnest Jun 03 '19 at 20:35
  • @ImportanceOfBeingErnest I tried the second comment. It did minimize the sticks but not the definite number I wanted. The another source code you cited `.datestr2num(date)` did work perfectly. The only problem is, it converter the dates into a number. The number of sticks is same as I wanted. – Msquare Jun 03 '19 at 20:47
  • For datetimes the number of ticks is rather unimportant because usually you do not want ticks at some 2019-04-19 14:23:46, but rather at the beginning of each month, or every monday, or everyday at noon or similar. – ImportanceOfBeingErnest Jun 04 '19 at 11:23

0 Answers0