Home > Blockchain >  How to fit the text above the bars plot in matplotlib?
How to fit the text above the bars plot in matplotlib?

Time:03-07

I used the plt.bar from matplotlib.pyplot but I have a problem making the text fit where it shows the text outside the box. So, I need to show the text above the bar with different font size and with space.

for rect in barp1   barp2   barp3   barp4   barp5   barp6   barp7   barp8:
    height = rect.get_height()
    plt.text(rect.get_x()   rect.get_width() / 2.0, height, f'{height:.2f}',fontsize=5, ha='center', va='bottom' ,rotation = 90)

enter image description here

CodePudding user response:

Some ideas:

  • add an extra space before the text, to create a natural padding
  • plt.margins(y=...) adds extra whitespace in the vertical direction (as the zero of the bars is "sticky", only whitespace at the top will be added)
  • the top and the right spines can be made invisible, to prevent the text being touched or crossed out by the top line
  • ax.spines['left'].set_bounds(0, 100) can be used to show the y-axis exactly up to 100
  • a FixedLocator can be used to only set ticks up till 100

The following code shows all these combined. Depending on your situation and preferences, you might choose one or more of them.

from matplotlib import pyplot as plt
from matplotlib.ticker import FixedLocator
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.rand(2, 8) * 100)

ax = df.plot.bar(legend=False)

for bar in ax.patches:
    height = bar.get_height()
    ax.text(bar.get_x()   bar.get_width() / 2.0, height, f' {height:.2f}', fontsize=10,
            ha='center', va='bottom', rotation=90)
ax.margins(y=0.20)
for sp in ['top', 'right']:
    ax.spines[sp].set_visible(False)
ax.spines['left'].set_bounds(0, 100)
ax.yaxis.set_major_locator(FixedLocator(np.arange(0, 101, 10)))

plt.tight_layout()
plt.show()

extra space for barplot texts

  • Related