How to set font size of Matplotlib axis Legend?

后端 未结 7 1585
渐次进展
渐次进展 2020-12-02 10:19

I have a code like this:

import matplotlib.pyplot as plt
from matplotlib.pyplot import *
from matplotlib.font_manager import FontProperties

fontP = FontProp         


        
相关标签:
7条回答
  • 2020-12-02 10:49

    I generally do in this way. Once the plot has been done i do the following

    plt.legend(loc=0, numpoints=1)
    leg = plt.gca().get_legend()
    ltext  = leg.get_texts()
    plt.setp(ltext, fontsize='small') 
    

    I don't know if this works for you

    0 讨论(0)
  • 2020-12-02 10:54

    Here is how to change the fontsize of the legend list and/or legend title:

    legend=plt.legend(list,loc=(1.05,0.05), title=r'$\bf{Title}$') #Legend: list, location, Title (in bold)
    legend.get_title().set_fontsize('6') #legend 'Title' fontsize
    plt.setp(plt.gca().get_legend().get_texts(), fontsize='12') #legend 'list' fontsize
    
    0 讨论(0)
  • 2020-12-02 10:58

    Inspired by the current top answer, I found a slightly more natural way to change the fontsizes in the legend. The fontsize argument sets the font size of each of the data labels, and the title_fontsize argument sets the fontsize of the title, if you give the legend a title.

    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    ax.plot([0,1,2],[2,1,2],label='test_data (fs=12)')
    ax.legend(fontsize=12, title='TITLE (fs=30)',title_fontsize=30)
    

    Gives a figure like this:

    0 讨论(0)
  • 2020-12-02 10:59

    This is the fastest:

    plt.legend(loc=2,prop={'size':6})
    
    0 讨论(0)
  • 2020-12-02 11:00

    This is definitely an old question, but was frustrating me too and none of the other answers changed the legend title fontsize at all, but instead just changed the rest of the text. So after banging my head against the matplotlib documentation for awhile I came up with this.

    legend = ax1.legend(loc=0, ncol=1, bbox_to_anchor=(0, 0, 1, 1),
               prop = fontP,fancybox=True,shadow=False,title='LEGEND')
    
    plt.setp(legend.get_title(),fontsize='xx-small')
    

    As of Matplotlib 3.0.3, you can also set it globally with

    plt.rcParams['legend.title_fontsize'] = 'xx-small'
    
    0 讨论(0)
  • 2020-12-02 11:00

    I don't know how to set it up for an individual plot, but I always do it globally:

    plt.rc('legend',**{'fontsize':6})
    
    0 讨论(0)
提交回复
热议问题