Matplotlib scatter plot automatically duplicate datetime xticks

Question:

In my dataframe I have, for each day, the mean value of cardiac frequency during the day and during the night that I previously calculated. The problem is that when I try to do a scatter plot, the values on the x axis get duplicated.

So this is my df.

       date     FC_mean_day    FC_mean_night
0   2022-12-28    79.43             74.11
1   2022-12-29    74.25             75.00
2   2022-12-30    75.75             74.40
3   2022-12-31    70.91             72.90
4   2023-01-01    68.43             73.00

date             datetime64[ns]
FC_mean_day             float64
FC_mean_night           float64
dtype: object

And this is what I have done to generate the scatter plot

fig,ax = plt.subplots()

plt.scatter(df5.date, df5.FC_mean_night, color= 'blue', label = 'Notte(22-06)', alpha=1, )
plt.scatter(df5.date, df5.FC_mean_day, color= 'yellow', label = 'Giorno(06-22)', alpha=1,)

my_format = mdates.DateFormatter('%d/%m/%y')

plt.rcParams["figure.figsize"] = (3,4)
plt.title("Media della Frequenza Cardiaca")
plt.xlabel('Data')
plt.ylabel('Valore')
plt.xticks(rotation = 90)
plt.legend(loc='center left', bbox_to_anchor=(1,0.5))
ax.yaxis.grid(color='grey', linestyle = 'dashed')
ax.set_axisbelow(True)
ax.xaxis.set_major_formatter(my_format)

plt.show()

And this is what it generates:

scatter with duplicates

I noticed that when I have some values in the next day and not the night the problem doesn’t happen, like in this case:

       date     FC_mean_day    FC_mean_night
0   2022-12-28    79.43             74.11
1   2022-12-29    74.25             75.00
2   2022-12-30    75.75             74.40
3   2022-12-31    70.91             72.90
4   2023-01-01    68.43             73.00
5   2023-01-02    75.00              NaN

scatter without duplicates

What am I missing?

Asked By: Tosamoon

||

Answers:

You already used a dateformatter, so you just need set a locator with Axis.set_major_locator.

ax.xaxis.set_major_formatter(my_format)

ax.xaxis.set_major_locator(mdates.DayLocator(interval=1)) # <- add this line

Output :

enter image description here

Answered By: Timeless
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.