1

In my code I have something like:

    import matplotlib.pyplot as plt
    
    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot()

    ...
    
    fmtstr = '{:<15}{:<15}{:<15}\n{:<15}{:<15}{:<15}\n{:<15}{:<15}{:<15}\n{:<15}{:<15}{:<15}'
    ntext = fmtstr.format('    ', 'tot', 'unique',
            'in  ', str(len(seqzs[fp])), str(len(seqzsSet[fp])),
            'std ', str(len(seqzs[std])), str(len(seqzsSet[std])),
            'shrd', '', str(len(dRTShrd)))

    ax.text(0.03, 0.8, ntext, transform=ax.transAxes)
    print(ntext)
    ...

    plt.savefig(os.path.join(outDir, oname))

The formatted text ntext looks good when printed:

               tot            unique         
in             6826           3837           
std            24773          11376          
shrd                          3220           

But not good in the plot: enter image description here

How do I get it right in the plot? (The widths of the numbers change with every plot so I need a constant formatter)

FNia
  • 173
  • 6
  • 2
    You need to use a [monospaced font](https://en.wikipedia.org/wiki/Monospaced_font). Check [this question on changing the plot font](https://stackoverflow.com/questions/21321670/how-to-change-fonts-in-matplotlib-python). – Aziz Feb 13 '22 at 09:25
  • @Aziz, this helped, thank you! All I had to do was edit to `ax.text(0.03, 0.8, ntext, transform=ax.transAxes, fontname = 'monospace')` – FNia Feb 13 '22 at 09:35

1 Answers1

1

Use monospace font like this: (Thanks to @Aziz for suggesting.)

    import matplotlib.pyplot as plt
    
    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot()

    ...
    
    fmtstr = '{:<7}{:<8}{:<9}\n{:<7}{:<8}{:<9}\n{:<7}{:<8}{:<9}\n{:<7}{:<8}{:<9}'  # format string
    ntext = fmtstr.format('    ', 'tot', 'unique',
            'in  ', str(len(seqzs[fp])), str(len(seqzsSet[fp])),
            'std ', str(len(seqzs[std])), str(len(seqzsSet[std])),
            'shrd', '', str(len(dRTShrd)))
    ax.text(0.03, 0.8, ntext, transform=ax.transAxes, fontname = 'monospace')

    ...

    plt.savefig(os.path.join(outDir, oname))

enter image description here

FNia
  • 173
  • 6