3

I have a bar plot which is being returned to me (i have access to the AxesSubplot object) which already has some labels on the bars. The issue is they are illegible and i would like to enlarge them (or clear and reset them). Take the following code for example:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'a':['red','green','blue'], 'b':[4,8,12]})
plot = df.plot(kind='barh')

for i in plot.patches:
    plot.text(i.get_width()+.01, i.get_y()+.38, str(i.get_width()), fontsize=31)

This generates a nice bar plot with labels on the bars. But lets say i want to remove or change those labels, how can this be done?

3
  • I don't understand, if you want to remove them, why don't you just omit the for i in plot.patches..., or to change the size, change the fontsize argument? Commented Oct 31, 2018 at 21:09
  • 1
    As i said in the question the plot is being returned to me (from a function call) so its already built into the object. The code is just a dummy example Commented Oct 31, 2018 at 21:11
  • Oh OK, I think I get it, see my answer below Commented Oct 31, 2018 at 21:18

1 Answer 1

8

You can access the text objects using plot.texts. In your example, you get:

>>> plot.texts
[Text(4.01,0.13,'4'), Text(8.01,1.13,'8'), Text(12.01,2.13,'12')]

You can remove them all in a loop:

for t in plot.texts:
    t.set_visible(False)

Or change attributes (fontsize for example) in a similar manner:

for t in plot.texts:
    # Reduce fontsize to 10:
    t.set_fontsize(10)
Sign up to request clarification or add additional context in comments.

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.