Sophia Xu
Sophia Xu

Reputation: 33

How to change the font size of axes labels of a histogram

I created a histogram of string occurrences based on a column of a pandas dataframe. The strings are quite long so when I plot the histogram, the labels get cut off. How do I change the size of the tick labels?

I am aware of set_xticklabels, but I'm not quite sure how to use this with the histogram I created.

Here's how I created my histogram:

assignments_df[['Major:']].apply(pd.value_counts).plot(kind = 'bar', subplots = True)
plt.savefig('Major_Distribution.png')

Upvotes: 3

Views: 13082

Answers (2)

Brendan
Brendan

Reputation: 4011

plt.xtics()

Look into the fontsize argument of plt.xticks():

df = pd.DataFrame({'x':np.random.rand(20) // .01,
                  'y':np.random.rand(20) // .01})

df.plot(kind='bar')
plt.xticks(fontsize=8)
plt.show()

enter image description here

With rotation

You could also look into rotating your tick labels:

# Different example data:
df = pd.DataFrame({'x':['abcdedf','abcdef','abcde','abcd'],
                  'y':np.random.rand(4) // .01})

df.plot(kind='bar', x='x', y='y')
plt.xticks(fontsize=8, rotation=45)
plt.show()

enter image description here

Horizontal

Yet another option is to make your bar chart horizontal. It still takes up space (horizontal rather than vertical) but makes longer labels easier to read.

df = pd.DataFrame({'x':['abcdedf','abcdef','abcde','abcd'],
                  'y':np.random.rand(4) // .01})

plt.barh('x', 'y', data=df)
plt.show()

enter image description here

Upvotes: 5

Ankit Agrawal
Ankit Agrawal

Reputation: 654

To change the font size you can use, assuming you have imported matplotlib.pyplot as plt

plt.xlabel('xlabel', fontsize=10)
plt.ylabel('ylabel', fontsize=10)

Upvotes: 2

Related Questions