0

I'm trying to make my legends align. Even if I make my strings the same size the font seems to make the alignment impossible.

I want the percentages to be aligned with the ones in the bottom.

import numpy as np
import matplotlib.pyplot as plt


fig, ax = plt.subplots(figsize=(5, 5))

data = list(df['Preço'])

total = df['Preço'].sum()
l = []
for x in list(df['Preço']):
    l.append("{0:.1%}".format(x/total))   
l

ativos = [x + ((maxlen - len(x)) * ' ' ) + '    ' for x in list(df['Nome do Ativo'])]
for i in range(len(l)):
    ativos[i] = ativos[i] + ((5 - len(l[i]))*' ') + l[i]


wedges, autotexts = ax.pie(data)

leg = ax.legend(wedges, ativos, title="Ativos \n", loc='lower center' , bbox_to_anchor=(0.5, -0.50, 0, 1), labelspacing=0.15)


plt.setp(autotexts, size=0)
ax.set_title(r"Composição")
plt.show()

enter image description here`

ap95btg
  • 27
  • 3

1 Answers1

0

Welcome to Stackoverflow.

This is happening because different characters in the standard font for legends have different widths. I presume that the text appears aligned in, for example, a terminal window because such windows typically use fixed-width fonts.

The simplest solution to your problem would be to set the legend font to a fixed-width font like Courier. This answer shows you how to do that,

holdenweb
  • 33,305
  • 7
  • 57
  • 77