метка даты по оси X python - PullRequest
       15

метка даты по оси X python

1 голос
/ 10 марта 2020

Мои данные выглядят примерно так

01.03.20    10
02.03.20    10
04.03.20    15
05.03.20    16

Я хочу построить dates против значений y и хочу, чтобы формат xaxis был похож на Mar 01 Mar 02 Mar 03 ...

Вот мой код:

fig, ax = plt.subplots()
ax.scatter(x, y, s=100, c='C0')
ax.plot(x, y, ls='-', c='C0')


# Set the locator
locator = mdates.MonthLocator()  # every month
# Specify the format - %b gives us Jan, Feb...
fmt = mdates.DateFormatter('%b-%d')

X = plt.gca().xaxis
X.set_major_locator(locator)
# Specify formatter
X.set_major_formatter(fmt)

ax.xaxis.set_tick_params(rotation=30)

Что-то не так, поскольку x-axis, xticks и xlabel не отображаются. Как я могу изменить формат xlabel, чтобы показать месяц и дату, например: Mar 01 Mar 02 Mar 03 ...

1 Ответ

2 голосов
/ 11 марта 2020

1) Я предполагаю, что ваша ось x содержит string, а не datetime. Затем, прежде чем строить график, я конвертирую его, как показано ниже.

x=[datetime.strptime(xi, "%d.%m.%y") for xi in x]

2) Если вы выберете MonthLocator, вы не сможете получить его как 01 марта ... Таким образом, переключите его с помощью DayLocator.

locator = mdates.DayLocator()

3) Этот код необязателен для использования кода очистки. Вам не нужно X.

ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(fmt)
ax.xaxis.set_tick_params(rotation=30)

Пример кода здесь.

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

x=["01.03.20", "02.03.20", "04.03.20", "05.03.20"]
x=[datetime.strptime(xi, "%d.%m.%y") for xi in x]
y=[10, 10, 15,16]

fig, ax = plt.subplots()
ax.scatter(x, y, s=100, c='C0')
ax.plot(x, y, ls='-', c='C0')

locator = mdates.DayLocator() 
fmt = mdates.DateFormatter('%b-%d')

ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(fmt)
ax.xaxis.set_tick_params(rotation=30)
ax.set_xlim(x[0],x[3])

plt.show()

Пример результата здесь.

enter image description here

...