aloha
aloha

Reputation: 4784

date label on x-axis python format

My data looks something like this

01.03.20    10
02.03.20    10
04.03.20    15
05.03.20    16

I want to plot the dates vs the y values and I want the format of the xaxis to be something similar to Mar 01 Mar 02 Mar 03 ...

Here's my code:

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)

Something is wrong as the x-axis, xticks, and xlabel is not showing. How can I change the format of the xlabel to show the month and the date eg: Mar 01 Mar 02 Mar 03 ...

Upvotes: 1

Views: 632

Answers (1)

ilke444
ilke444

Reputation: 2741

1) I assume your x axis contains string, not datetime. Then, before plotting I would convert it as below.

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

2) If you select MonthLocator, you cannot get it as Mar 01... Thus, switch it with a DayLocator.

locator = mdates.DayLocator()

3) This one is optional to have cleaner code. You don't need X.

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

Sample code is here.

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()

Sample result is here.

enter image description here

Upvotes: 2

Related Questions