vojtam
vojtam

Reputation: 1245

How to put only Mondays on xticks in matplotlib

I have the following code:

import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.dates import MO, WeekdayLocator

sns.lineplot(x="datum", y="people", data=data_s, hue="expedice")
plt.ylabel("People")
plt.xlabel("Datum")

loc = WeekdayLocator(byweekday=MO, interval=1)

plt.xticks(rotation=90)
plt.legend(loc = 'upper right', bbox_to_anchor=(1.2, 0.5))
plt.show()

which gives me this output:

enter image description here

But I would like to display only every Monday on xticks, because now it is not legible at all. How can I do this please?

Upvotes: 1

Views: 777

Answers (1)

tdy
tdy

Reputation: 41327

Currently the locator gets created but is never actually applied, and also the x ticks look like they might be strings instead of datetimes, so:

  1. Make sure the dates have been converted to_datetime
  2. Apply the WeekdayLocator using set_major_locator
import pandas as pd
from matplotlib.dates import MO, WeekdayLocator

#1 convert to datetime
data_s["datum"] = pd.to_datetime(data_s["datum"])

ax = sns.lineplot(x="datum", y="people", data=data_s, hue="expedice")

#2 apply weekday locator
loc = WeekdayLocator(byweekday=MO, interval=1)
ax.xaxis.set_major_locator(loc)

Upvotes: 1

Related Questions