Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop the date from a matplotlib time series plot

I have a simple time series plot in Pandas, that can be emulated by the following code below:

import pandas as pd
import numpy as np
from datetime import datetime, timedelta, date
import time
import matplotlib.pyplot as plt

df2 = pd.DataFrame({'A' : np.random.rand(1440).cumsum()}, index = pd.date_range('1/1/2015', periods=1440, freq='1min'))

df2.A.plot()

Which generates the following graph: enter image description here

My problem is that the date displayed is not relevant to the graph itself and I wish to remove it and leave only the time series on the x axis.

How do I do this?

like image 966
BML91 Avatar asked Aug 11 '15 11:08

BML91


People also ask

How do I change the date format in matplotlib?

Using the DateFormatter module from matplotlib, you can specify the format that you want to use for the date using the syntax: "%X %X" where each %X element represents a part of the date as follows: %Y - 4 digit year with upper case Y. %y - 2 digit year with lower case y. %m - month as a number with lower case m.

How do I format a date axis in matplotlib?

MatPlotLib with Python Create a figure and a set of subplots using subplots() method. Plot the dataframe using plot method, with df's (Step 1) time and speed. To edit the date formatting from %d-%m-%d to %d:%m%d, we can use set_major_formatter() method. Set the formatter of the major ticker.

Is PLT show () necessary?

Show() would help whenever there is no interactive plot. fig. Show() would help to display all the figures if it is interactive. Let's take an example to observe the difference between plt.


1 Answers

you can use matplotlib.dates and its HourLocator to set the date/time formatting:

import pandas as pd
import numpy as np
from datetime import datetime, timedelta, date
import time
import matplotlib.pyplot as plt
import matplotlib.dates as dates

df2 = pd.DataFrame({'A' : np.random.rand(1440).cumsum()}, index = pd.date_range('1/1/2015', periods=1440, freq='1min'))

df2.A.plot()
plt.gca().xaxis.set_major_locator(dates.HourLocator())
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%H:%M'))

plt.show()

enter image description here

like image 128
tmdavison Avatar answered Sep 18 '22 00:09

tmdavison