Issue
I have a pandas Series with integer running hours as index, where the hours do not start at midnight but rather on a random hour (8 in the example below).
hour = range(8, 24) + range(0, 8)
values = pd.Series(range(24), index=hour)
I wish to plot a 24-hours graph of the values, but I want the x-axis to show the "raw" hour values and not re-arrange the index.
ax = values.plot()
ax.axis([0, 23, 0, 23])
Any suggestions?
Solution
One option is indeed (as you said yourself in the comments) to use a non-numeric index.
import pandas as pd
import matplotlib.pyplot as plt
hour = range(8, 24) + range(0, 8)
values = pd.Series(range(24), index=list(map(str,hour)))
ax = values.plot()
plt.show()
Since this will automatically choose some labels and there is no way to control them, it might not be optimal.
A better solution is probably to use a different index, namely one that is numeric and continuously increasing (in this case from 8 to 31) and then modify the ticklabels as the modulo of 24.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker
hour = range(8, 24) + range(0, 8)
values = pd.Series(range(24), index=hour)
values.index = values.index[0]+np.arange(0,len(values))
ax = values.plot()
func = lambda x,pos: "{:g}".format(x%24)
ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(func))
plt.show()
This would then also allow to set the locations to multiples of some number (e.g.6) which makes sense for hours in a day.
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(6))
Finally you could of course opt for using real datetimes.
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
hour = range(8, 24) + range(0, 8)
values = pd.Series(range(24), index=hour)
todate = lambda i: datetime(2017,11,8+(values.index[0]+i)//24,(values.index[0]+i)%24)
values.index = [todate(i) for i in range(len(values))]
ax = values.plot()
plt.show()
Answered By - ImportanceOfBeingErnest
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.