13

pandas.DataFrame.plot is a convenient method for plotting data from dataframes. However, I don't understand how to format the axes using this method. For example,

import pandas as pd
import datetime

df = pd.DataFrame(index =  [datetime.datetime(2016, 7, 2, 0, 0),
                    datetime.datetime(2016, 8, 6, 0, 0),
                    datetime.datetime(2016, 9, 13, 0, 0),
                    datetime.datetime(2016, 10, 26, 0, 0),
                    datetime.datetime(2016, 11, 2, 0, 0)],
                    data = {'total' : [5, 3, 1, 0, 2]})

df

Output

          total
2016-07-02  5
2016-08-06  3
2016-09-13  1
2016-10-26  0
2016-11-02  2

Now plotting with the pandas plot method:

df.plot(kind='bar')

example bar chart

I would prefer that the x-axis just have the labels as the three-letter format of month - Jul Aug Sep Oct Nov.

Is this possible with the pandas plot method or should I build a chart with matplotlib instead?

2 Answers 2

15

I found a simpler way to change the x labels to month only.

import pandas as pd
import datetime

df = pd.DataFrame(index =  [datetime.datetime(2016, 7, 2, 0, 0),
                    datetime.datetime(2016, 8, 6, 0, 0),
                    datetime.datetime(2016, 9, 13, 0, 0),
                    datetime.datetime(2016, 10, 26, 0, 0),
                    datetime.datetime(2016, 11, 2, 0, 0)],
                    data = {'total' : [5, 3, 1, 0, 2]})

ax = df.plot(kind='bar')
x_labels = df.index.strftime('%b')
ax.set_xticklabels(x_labels)

plt.show()

example chart

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

Comments

10

If you want to show the graph as a categorical bar plot, i.e. equidistant bars independent of the actual date, you can just reformat the xticklabels,

f = lambda x: datetime.datetime.strptime(x, '%Y-%m-%d %H:%M:%S').strftime('%b')
ax.set_xticklabels([ f(x.get_text()) for x in ax.get_xticklabels()])

where %b is the month's abbreviated name and ax is the axes of your plot.

Complete example:

import pandas as pd
import datetime
import matplotlib.pyplot as plt

df = pd.DataFrame(index =  [datetime.datetime(2016, 7, 2, 0, 0),
                    datetime.datetime(2016, 8, 6, 0, 0),
                    datetime.datetime(2016, 9, 13, 0, 0),
                    datetime.datetime(2016, 10, 26, 0, 0),
                    datetime.datetime(2016, 11, 2, 0, 0)],
                    data = {'total' : [5, 3, 1, 0, 2]})

ax = df.plot(kind='bar')

f = lambda x: datetime.datetime.strptime(x, '%Y-%m-%d %H:%M:%S').strftime('%b')
ax.set_xticklabels([ f(x.get_text()) for x in ax.get_xticklabels()])

plt.show()

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.