Format the x axis in a chart created using the pandas build method

pandas.DataFrame.plot is a convenient way to print data from data frames. However, I do not understand how to format the axes using this method. For instance,

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 let's plot using the pandas construction method:

 df.plot(kind='bar') 

approximate histogram

I would prefer that the x axis have labels in the form of a three-letter month format - July August September October November.

Is this possible using the pandas build method or do I need to build a chart using matplotlib?

+5
source share
2 answers

I found an easier way to change x labels for only a month.

 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() 

sample chart

+2
source

If you want to show the chart as a categorical hatching chart, that is, equidistant bars that are independent of the actual date, you can simply reformat 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 abbreviated name of the month and ax is the axis of your plot.

Full 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

+6
source

Source: https://habr.com/ru/post/1268768/


All Articles