Lineplot doesn't show all dates in axis

10,980

Solution 1

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

Solution 2

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.

Share:
10,980
adhg
Author by

adhg

SOreadytohelp

Updated on June 04, 2022

Comments

  • adhg
    adhg almost 2 years

    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

    • ImportanceOfBeingErnest
      ImportanceOfBeingErnest over 5 years
      Just as with usual plots, you see nicely fitting labels, here, every half year. Do you want to show lables on each location that has data in the plot? (Note that in that case labels would probably overlap)
    • adhg
      adhg over 5 years
      @ ImportanceOfBeingErnest correct, I'm aware of the overlap and this is why I added a rotation (45 or 90). I understand that the 'default' will present it neatly but for this purpose the dates (text) are critical. Thanks
    • ImportanceOfBeingErnest
      ImportanceOfBeingErnest over 5 years
      So does adding xticks=df.Date into .set() do what you're after?
    • adhg
      adhg over 5 years
      So If I understand you correctly, I did: ax.set(xlabel="Date", ylabel="mpta", ticks=df_dry['Date']) return result: AttributeError: Unknown property ticks
    • adhg
      adhg over 5 years
      I get: Cannot compare type 'Timestamp' with type 'float'. Just to be sure: I checked and the Date is pandas.core.series.Series (type(df_dry['Date'])