0

I'm plotting a dataframe which its index is of type datetime (like 2018-05-29 08:20:00).

I slice the data based on last hour and last day and last week and last month and then I plot them.

The data is collected every one minuet. So, the index of each row differs only one minute.

When I plot the data for last hour, the x axis is plotted like:

enter image description here

Or, for the last month it is like:

enter image description here

which is clean and readable. But, when I plot the last day data the x-axis index is like:

enter image description here

Why it is overlapped? how to fix it?

the codes to plot these time frames are the same, just the given dataframe is changed:

self.canvas.axes.plot(df_day.index, df_day.loc[:, item], linestyle="None", marker='.')
                      # or df_month or df_week or df_hour

how to make a the x-axis index as the format that I want? I want it to be printed as hour:minute for last hour, or day hour:minute for last day.

I tried the links, but none of them helped:

I tried

self.canvas.axes.xaxis.set_major_formatter(self.major_formatter, self.canvas.axes.get_xticklabels())

@ticker.FuncFormatter
def major_formatter(x, pos):
    return datetime.datetime.fromtimestamp(x.day / 1e3)

but it returned int46 in x variable, so it wasn't helping.

3
  • Check out autofmt_xdate matplotlib.org/3.1.2/_modules/matplotlib/figure.html Commented Aug 5, 2020 at 6:09
  • @DavidHoffman it only rotates the x-indexes. it's good for the overlapping problem, thanks but how to define my own formats? btw, link is broken(error 404) Commented Aug 5, 2020 at 6:19
  • Check this out. You can specify the format as a string. Commented Aug 5, 2020 at 7:23

1 Answer 1

2

from the first answer to How to plot day and month which is also an answer from question owner I found the solution:

import matplotlib.dates as mdates
import matplotlib.pyplot as plt 

fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(date, price , label="Price")
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))

or in my case:

self.canvas.axes.xaxis.set_major_formatter(mdates.DateFormatter('%d-%b'))

from strftime() and strptime() Format Codes¶, one can learn about formats of dates and times.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.