0

I have data like below 83 rows and 2 columns

x1.head()

     x          y
79  2021-01-10  3755
80  2021-01-17  3680
81  2021-01-24  4192
82  2021-01-31  4587
83  2021-02-07  4398

But when i plot it using

plt.figure(figsize=(15,10))
plt.grid()
plt.plot(x1['x'], x1['y']);

my x axis appears as below - in Year-month format. I would like to keep the format same as column x.

  1. How to fix that?
  2. why does it changes date format?
  3. how to ensure that we get all x-axis labels

enter image description here

Jody Klymak
  • 4,979
  • 2
  • 15
  • 31
user2543622
  • 5,760
  • 25
  • 91
  • 159

1 Answers1

1

Try using 'DateFormatter ', in which you specify that you want to display year, month, day on the axis. For example, you can leave only the year and see how it works.

ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y'))

The following is the code where the x1 column is converted to a date and the DateFormatter specifies the year, month, day.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates

x1 = pd.DataFrame({'x': ['2021-01-10', '2021-01-17', '2021-01-24', '2021-01-31', '2021-02-07'],
                   'y': [3755, 3680, 4192, 4587, 4398]})

x1['x'] = pd.to_datetime(x1['x'])

fig, ax = plt.subplots(figsize=(30,10))
plt.xlim(x1.loc[0,'x'], x1.loc[len(x1)-1,'x'])
ax.plot(x1['x'], x1['y'])
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y-%m-%d'))
ax.xaxis.set_major_locator(matplotlib.ticker.LinearLocator(5))
fig.autofmt_xdate()

plt.show()
inquirer
  • 4,286
  • 2
  • 9
  • 16
  • 1
    even if I drop lines `ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y-%m-%d')) fig.autofmt_xdate()` from your code, it prints in ymd format so I am not sure whether `set_major_formatter` is working or not – user2543622 Aug 04 '22 at 17:58
  • 1
    also is there need of `x1['x'] = pd.to_datetime(x1['x'])`. Even without doing that line I get below output `x1.dtypes x1.dtypes x datetime64[ns] y int64 dtype: object` – user2543622 Aug 04 '22 at 17:59
  • I used pd.to_datetime because I wasn't sure if the column type was in date format(have it in this case in string format). In what format do you need the date year, month, day, that is, divisions should look like this 2021-01-10? You can use your data instead of my x1 frame and check. – inquirer Aug 04 '22 at 19:45
  • 1
    also i noticed the dates that are printed are first of every other month. How to force to use values from our column `x`? – user2543622 Aug 04 '22 at 20:04
  • Updated the code. Specified size assignment. Also added LinearLocator, in which 5 means how many labels to draw along the axis. As for exactly displaying the labels from the column, I can’t say yet. Possibly tomorrow. – inquirer Aug 04 '22 at 20:27
  • Updated code, set x-axis limits: plt.xlim(x1.loc[0,'x'], x1.loc[len(x1)-1,'x']). Now only the data that is in the column is displayed, at least it works for me. – inquirer Aug 04 '22 at 20:43