Using pandas' plot method, I am trying to plot the columns in a pandas DataFrame whose index consists of dates with regular spacing except the last one.
For some reason, superfluous tick marks appear on the x-axes of the plots. How can I get rid of these superfluous tick marks while continuing to use pandas' plot method?
I am pasting below a self-contained code that reproduces the problem and a screenshot of the output in which I have marked some of the superfluous tick marks. I am using Python 3.10.4, pandas 1.4.2, Numpy 1.22.3, and Matplotlib 3.5.2.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
x = np.arange(-3, 3, 0.1)
dates = pd.date_range(end=dt.date(2022, 9, 30), freq="Q", periods = len(x), name="date")
y1 = np.sin(x)
y2 = np.cos(x)
trig = pd.DataFrame({"sin": y1, "cos": y2}, index = dates)
extra_date = pd.date_range(end=dt.date(2022, 10, 19), freq="D", periods = 1, name="date")
extra = pd.DataFrame({"sin": np.sin(2.91), "cos": np.cos(2.91)}, index = extra_date)
trig = pd.concat([trig, extra])
fig, axes = plt.subplots(2, 1, figsize=(15, 7), sharex=True)
trig.sin.plot(ax=axes[0], grid=True, style=["o-"], rot=0, title="Sin")
trig.cos.plot(ax=axes[1], grid=True, style=["o-"], rot=0, title="Cos")
for ax in axes:
for label in ax.xaxis.get_ticklabels():
label.set_ha('center')
plt.show()
The problem disappears when I allow each plot to have a separate x-axis by removing the sharex=True
from plt.supbplots()
but I don't want the plots to have separate x-axes and I wish to continue using pandas' plot method.
I have looked at various shared x-axis tick mark-related Q&As involving dates, Matplotlib, and pandas on Stack Overflow but could not find anyting solving this problem without requiring me to give up on pandas' plot method.
CodePudding user response:
Modify the for loop as
for ax in axes:
ax.minorticks_off()
for label in ax.xaxis.get_ticklabels():
label.set_ha('center')