Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

python - Fix size of legend in matplotlib

I am trying to make automated plots with matplotlib, with several different features plotted on top of one another (the background is a filled contour plot, one level above is a pcolormesh). The topmost feature that I'm trying to plot is several scatter plots, with different labels and icons.

I'm trying to add a legend to this plot, currently using the following commands:

leg = ax.legend(legplots,
           legnames,
           scatterpoints=1,
           loc='upper center',
           ncol=3,
           fontsize=14,
         bbox_to_anchor=(0.5, -0.14),
          fancybox=True, shadow=True)

Assume that ax is the main axes, and that legplots and legnames are lists of scatter plots and their appropriate labels respectively.

Adding the legend works correctly, but as the number of legplots that I have (and their name lengths) vary, as you animate the plots, the legend grows and shrinks in size. How do I control the size of the legend box and the column widths inside the legend? Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

At the moment your bounding box has a size of 0, since you only specify its position ((0.5, -0.14)).

You can set the bounding box of the legend to be bigger than 0 and also big enough for the maximum size that it needs to have for the maximum number of elements to fit in. I think you will need to find that size by trial and error.

So using the full 4-tuple notation

bbox_to_anchor=(x0, y0, width, height)

in conjunction with an appropriate loc parameter and the keyword argument mode="expand" will allow you to make the legend big enough for your needs. For a more detailed explanation about the 4-tuple notation see this post and also look at the legend location guide.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...