Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format x-axis on chart created with pandas plot method

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?

like image 243
edge-case Avatar asked Jun 12 '17 09:06

edge-case


People also ask

How do you change the X-axis labels on a pandas plot?

You can set the labels on that object. Or, more succinctly: ax. set(xlabel="x label", ylabel="y label") . Alternatively, the index x-axis label is automatically set to the Index name, if it has one.

What is the default plot () type in pandas plotting?

With a DataFrame , pandas creates by default one line plot for each of the columns with numeric data.

Can pandas generate graphics plots?

There are tons of plotting libraries available to plot the pandas data frames. These include but not limited to Matplotlib, Plotly, Seaborn, Bokeh, and many more to come. Pandas has its own plotting API which uses Matplotlib under the hood. There are many plotting options and support for almost every type of plot.


1 Answers

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

like image 194
edge-case Avatar answered Oct 18 '22 19:10

edge-case