jackd
jackd

Reputation: 357

How to format legend title to font type monospace in matplotlib?

I want to format the legend title to be monospace. I have:

    width = 8
    print_slope     = "{0:.5F}".format(slope)
    print_intercept = "{0:.5F}".format(intercept)
    print_r_squared = "{0:.5F}".format(r_value**2)
    ax.legend(prop={'family': 'monospace'},title='Slope:     '+str(print_slope.rjust(width))+'\nIntercept: '+str(print_intercept.rjust(width))+'\nR-squared: '+str(print_r_squared.rjust(width)))

Yet the output I get gives me the legend title in variable width, with the series in monospace:

enter image description here

How do I get the title to be monospace also? Thanks.

Upvotes: 4

Views: 4233

Answers (2)

nieswand
nieswand

Reputation: 43

You can use the keyword argument title_fontproperties of legend():

ax.legend(..., title_fontproperties={'family': 'monospace'})

Upvotes: 0

Paul H
Paul H

Reputation: 68116

I think you can set the legend's title with a separate call.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [3, 2, 1], 'k-', label='data')
leg = ax.legend(prop={'size': 20})
leg.set_title('Legend Title', prop={'size': 14, 'weight': 'heavy'})

enter image description here

Upvotes: 4

Related Questions