matplotlib图例水平排列
参考:matplotlib legend horizontal
在matplotlib中,图例是用来标识不同数据系列或不同类别的标记和颜色的标签。有时候我们希望将图例水平排列,以节省空间并使得图例更加美观。本文将介绍如何在matplotlib中实现图例的水平排列。
方法一:使用legend的loc
参数
我们可以通过legend函数的loc
参数来指定图例的位置,其中loc的取值可以是best
、upper right
、upper left
、lower left
、lower right
、right
、center left
、center right
、lower center
、upper center
、center
,其中best
表示最佳位置。
Output:
在这个示例中,我们使用loc='center'
将图例放在图的中心位置,并通过bbox_to_anchor=(0.5, -0.15)
和ncol=2
参数使得图例水平排列,且一行显示两个标签。
方法二:使用legent
函数的mode
参数
除了使用loc
参数外,我们还可以使用mode
参数来控制图例的水平排列。mode
参数的取值可以是expand
、expand_left
、expand_right
,其中expand
表示图例会水平排列,而expand_left
和expand_right
会使得图例靠左或靠右排列。
Output:
在这个示例中,我们使用mode='expand'
让图例水平排列。
方法三:使用legend
函数的title_orientation
参数
另外,我们还可以通过legend
函数的title_orientation
参数来调整图例标题的方向。当title_orientation
参数的值为horizontal
时,图例标题水平显示;当title_orientation
参数的值为vertical
时,图例标题垂直显示。
在这个示例中,我们使用title_orientation='horizontal'
将图例标题水平显示。
方法四:使用legend
函数的handlelength
参数
最后,我们还可以通过legend
函数的handlelength
参数来调整每个图例标签的长度,以使得图例水平排列更加美观。
Output:
在这个示例中,我们使用handlelength=2.5
将图例标签的长度设置为2.5。