Matplotlib отображает только годы вместо каждого 1 января на оси x, содержащей даты - PullRequest
0 голосов
/ 13 февраля 2020

У меня есть этот фрейм данных:

import pandas as pd
import datetime
from sklearn.utils import check_random_state
import math
start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y")
end = datetime.datetime.strptime("17-03-2017", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
X = [d.strftime('%d-%m-%Y') for d in date_generated] # I need this format for my real dataframe
Y = [math.cos(i) for i in range(1000)]
df = pd.DataFrame(dict(date=X,value=Y))

df.head(3)
         date     value
0  21-06-2014  1.000000
1  22-06-2014  0.540302
2  23-06-2014 -0.416147

df.tail(3)
           date     value
997  14-03-2017 -0.440062
998  15-03-2017  0.517847
999  16-03-2017  0.999650

Когда я строю два столбца моего фрейма данных следующим образом, ось X не читается:

from matplotlib import pyplot as plt
plt.figure(figsize=(20, 5))
plt.plot(df["date"].values,df["value"].values)
plt.show()

enter image description here

Как можно отобразить только годы, по одному разу вместо каждого 1 января? В этом случае я бы хотел, чтобы только 2015, 2016 и 2017 годы отображались по оси x

1 Ответ

1 голос
/ 13 февраля 2020

Вы можете использовать matplotlib.dates locator и formatter для непосредственного форматирования datetime объектов, которые вы хотите поместить в xaxis:

import pandas as pd
import datetime
from sklearn.utils import check_random_state
import math
from matplotlib import pyplot as plt
import matplotlib.dates as mdates

start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y")
end = datetime.datetime.strptime("17-03-2017", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
Y = [math.cos(i) for i in range(1000)]


formatter = mdates.DateFormatter("%Y") ### formatter of the date
locator = mdates.YearLocator() ### where to put the labels

fig = plt.figure(figsize=(20, 5))
ax = plt.gca()
ax.xaxis.set_major_formatter(formatter) ## calling the formatter for the x-axis
ax.xaxis.set_major_locator(locator) ## calling the locator for the x-axis
plt.plot(date_generated, Y)
# fig.autofmt_xdate() # optional if you want to tilt the date labels - just try it
plt.tight_layout()
plt.show()

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...