matplotlib中的legend()——用于显示图例
legend()的一个用法:
当我们有多个 axes时,我们如何把它们的图例放在一起呢??
我们可以这么做:
import matplotlib.pyplot as plt import numpy as np x = np.arange(1, 11) fig = plt.figure(1) ax1 = plt.subplot(2, 1, 1) ax2 = plt.subplot(2, 1, 2) l1, = ax1.plot(x, x*x, 'r') #这里关键哦 l2, = ax2.plot(x, x*x, 'b') # 注意 plt.legend([l1, l2], ['first', 'second'], loc = 'upper right') #其中,loc表示位置的; plt.show()
在legend的参数中, loc参数设置图例的显示位置的:
'best' : 0, (only implemented for axes legends)(自适应方式) 'upper right' : 1, 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10,
另外,还有控制位置的重要参数:bbox_to_anchor(num1, num2), bbox_to_anchor被赋予的二元组中,第一个数值用于控制legend的左右移动,值越大越向右边移动,第二个数值用于控制legend的上下移动,值越大,越向上移动。
其它参数看这里有:
Keyword Description loc a location code prop the font property (matplotlib.font_manager.FontProperties 对象) eg song_font = matplotlib.font_manager.FontProperties(fname='simsun.ttc', size=8) fontsize the font size (和prop互斥,不可同时使用) markerscale the relative size of legend markers vs. original numpoints the number of points in the legend for line scatterpoints the number of points in the legend for scatter plot scatteryoffsets a list of yoffsets for scatter symbols in legend frameon if True, draw a frame around the legend. If None, use rc fancybox if True, draw a frame with a round fancybox. If None, use rc shadow if True, draw a shadow behind legend ncol number of columns borderpad the fractional whitespace inside the legend border labelspacing the vertical space between the legend entries handlelength the length of the legend handles handleheight the length of the legend handles handletextpad the pad between the legend handle and text borderaxespad the pad between the axes and legend border columnspacing the spacing between columns title the legend title bbox_to_anchor the bbox that the legend will be anchored. bbox_transform the transform for the bbox. transAxes if None.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架