Lineplot doesn't show all dates in axis

Viewed 12245

I have the followings:

fig, ax = plt.subplots(figsize=(40, 10))
sns.lineplot(x="Date", y="KFQ imports", data=df_dry, color="BLACK", ax=ax)
sns.lineplot(x="Date", y="QRR imports", data=df_dry, color="RED",ax=ax)

ax.set(xlabel="Date", ylabel="Value", )
x_dates = df_dry['Date'].dt.strftime('%b-%Y')
ax.set_xticklabels(labels=x_dates, rotation=45)

Result enter image description here

When I use a barchart (sns.barplot) the entire spectrum of dates are shown. Am I missing something for the line chart? I

2 Answers

The idea would be to set the xticks to exactly the dates in your dataframe. To this end you can use set_xticks(df.Date.values). It might then be good to use a custom formatter for the dates, which would allow to format them in the way you want them.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates
import seaborn as sns

df = pd.DataFrame({"Date" : ["2018-01-22", "2018-04-04", "2018-12-06"],
                   "val"  : [1,2,3]})
df.Date = pd.to_datetime(df.Date)


ax = sns.lineplot(data=df, x="Date", y="val", marker="o")
ax.set(xticks=df.Date.values)
ax.xaxis.set_major_formatter(dates.DateFormatter("%d-%b-%Y"))
plt.show()

enter image description here

Note how the same can be achieved without seaborn, as

ax = df.set_index("Date").plot(x_compat=True, marker="o")
ax.set(xticks=df.Date.values)
ax.xaxis.set_major_formatter(dates.DateFormatter("%d-%b-%Y"))
plt.show()

One way to circumvent the date tick sparsification from Seaborn is to convert the date column to string values.

df['dates_str'] = df.dates.astype(str)

Plotting using the new column as the x-axis will show all the dates.

Related