Reputation: 1197
I've drawn this chart from an API, so I can't provide the data. The x axis are dates and prices like this:
price
date
2022-12-18 1.19
2022-12-19 1.19
2022-12-20 1.19
2022-12-21 1.19
2022-12-22 1.19
What I want to change is what is in the red circle from "Jan\n2023" to "Jan-23" the rest is ok. What I've used in the code is this:
fig, ax = plt.subplots(figsize=(12, 6), constrained_layout=True)
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
ax.xaxis.set_major_formatter(
mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))
ax.xaxis.set_minor_locator(mdates.MonthLocator(bymonthday=(15)))
data_toplot.plot(ax=ax)
for label in ax.get_xticklabels(which='major'):
label.set(rotation=0, horizontalalignment='center')
But I don't know what is called to look for it myself because you can see the the days are minor ticks are that day is a major tick but also the one on the 18 a 3 day. So I don't know what function to use.
Upvotes: 1
Views: 53
Reputation: 13528
Here is an example to illustrate one way to do it:
import pandas as pd
df = pd.DataFrame(
{
"date": ["2022-12-18", "2022-12-19", "2022-12-20", "2022-12-21", "2022-12-22"],
"price": [1.19, 2.19, 5.19, 3.19, 4.19],
}
)
# Plot dataframe as is
from matplotlib import pyplot as plt
plt.plot(df["date"], df["price"])
Output:
# Plot the dataframe, but replace tick "2022-12-21" with "9999-99-99"
plt.xticks(
ticks=range(df["date"].shape[0]),
labels=[x if x != "2022-12-21" else "99-99-9999" for x in df["date"]],
)
plt.plot(df["date"], df["price"])
Output:
Upvotes: 1