Add labels and title to a plot made using pandas

Viewed 7883

I made a simple histogram using the following code:

a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
pd.Series(a).value_counts().plot('bar')

barplot of counts

Although this is a concise way to plot frequency histogram, I am not sure how to customize the plot i.e. :

  1. Add Title
  2. Add Axis Labels
  3. Sort values on x-axis
3 Answers

Series.plot (or DataFrame.plot) returns a matplotlib axis object which exposes several methods. For example:

a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
ax = pd.Series(a).value_counts().sort_index().plot('bar')
ax.set_title("my title")
ax.set_xlabel("my x-label")
ax.set_ylabel("my y-label")

updated plot

n.b.: pandas uses matplotlib as a dependency here, and is exposing matplotlib objects and api. You can get the same result via import matplotlib.pyplot as plt; ax = plt.subplots(1,1,1). If you ever create more than one plot at a time, you will find the ax.<method> far more convenient than the module level plt.title('my title'), because it defines which plot title you'd like to change and you can take advantage of autocomplete on the ax object.

You can use matplotlib to customize it. You can see I used .sort_index() to sort the xlabels.

import matplotlib.pyplot as plt

a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
pd.Series(a).value_counts().sort_index().plot(kind='bar')
plt.title('My Title')
plt.xlabel('My X Label')

As mentioned in the comments you can now just use the title, xlabel, and ylabel parameters (and use the kind parameter for the plot type):

a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']    
pd.Series(a).value_counts().plot(kind='bar', title="Your Title", xlabel="X Axis", ylabel="Y Axis")

See the Pandas plot() docs for more info.

Related