4

I have a pandas series with Timestamp indices that I'd like to plot.

print example.head()

2015-08-11 20:07:00-05:00    26
2015-08-11 20:08:00-05:00    66
2015-08-11 20:09:00-05:00    71
2015-08-11 20:10:00-05:00    63
2015-08-11 20:11:00-05:00    73

But when i plot it in pandas with:

plt.figure(figsize = (15,8))
cubs1m.plot(kind='area')

I'd like the values on the y-axis to show up in AM/PM format (8:08PM), not military time(20:08). Is there an easy way to do this?

And also, how would I control # of ticks and # of labels plotting with pandas?

Thanks in advance.

smci
  • 32,567
  • 20
  • 113
  • 146
SpicyClubSauce
  • 4,076
  • 13
  • 37
  • 62

1 Answers1

1

Your question has two elements:

  1. How to control # of ticks/labels on a plot
  2. How to change 24-hour time to 12-hour time

Axes methods set_xticks, set_yticks, set_xticklabels, and set_yticklabels control the ticks and the labels:

import matplotlib.pyplot as plt

plt.plot(range(10), range(10))
plt.gca().set_xticks(range(0,10,2))
plt.gca().set_xticklabels(['a{}'.format(ii) for ii in range(0,10,2)])

To change the time format, use pd.datetime.strftime: How can I convert 24 hour time to 12 hour time?

import pandas as pd

data = pd.Series(range(12), index=pd.date_range('2016-2-3 9:00','2016-2-3 20:00', freq='H'))
ax = data.plot(xticks=data.index[::2])
ax.set_xticklabels(data.index[::2].map(lambda x: pd.datetime.strftime(x, '%I %p')))

This question covers an alternate approach to plotting with dates: Pandas timeseries plot setting x-axis major and minor ticks and labels

Community
  • 1
  • 1
Gordon Bean
  • 4,272
  • 1
  • 32
  • 47