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.

Shahriar.M
  • 818
  • 1
  • 11
  • 24
  • Check out `autofmt_xdate` https://matplotlib.org/3.1.2/_modules/matplotlib/figure.html – David Hoffman Aug 05 '20 at 06: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) – Shahriar.M Aug 05 '20 at 06:19
  • Check [this](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure.autofmt_xdate) out. You can specify the format as a string. – Parth Shah Aug 05 '20 at 07:23

1 Answers1

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.

Shahriar.M
  • 818
  • 1
  • 11
  • 24