matplotlib图例legend语法及设置的方法

1.图例legend基础语法及用法

legend语法参数如下: matplotlib.pyplot.legend(*args, **kwargs)

Keyword Description
loc Location code string, or tuple (see below).图例所有figure位置
prop the font property字体参数
fontsize the font size (used only if prop is not specified)
markerscale the relative size of legend markers vs. original 图例标记与原始标记的相对大小
markerfirst If True (default), marker is to left of the label. 如果为True,则图例标记位于图例标签的左侧
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 the legend on a patch (frame). 控制是否应在图例周围绘制框架
fancybox If True, draw the frame with a round fancybox. 控制是否应在构成图例背景的FancyBboxPatch周围启用圆边
shadow If True, draw a shadow behind legend. 控制是否在图例后面画一个阴影
framealpha Transparency of the frame. 控制图例框架的 Alpha 透明度
edgecolor Frame edgecolor.
facecolor Frame facecolor.
ncol number of columns 设置图例分为n列展示
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 height 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.

(1)设置图例位置

使用loc参数


0: ‘best'

1: ‘upper right'

2: ‘upper left'

3: ‘lower left'


4: ‘lower right'

5: ‘right'

6: ‘center left'


7: ‘center right'

8: ‘lower center'

9: ‘upper center'

10: ‘center'

(2)设置图例字体

#设置字体大小
fontsize : int or float or {‘xx-small', ‘x-small', ‘small', ‘medium', ‘large', ‘x-large', ‘xx-large'}

(3)设置图例边框及背景

plt.legend(loc='best',frameon=False) #去掉图例边框
plt.legend(loc='best',edgecolor='blue') #设置图例边框颜色
plt.legend(loc='best',facecolor='blue') #设置图例背景颜色,若无边框,参数无效

(4)设置图例标题

plt.legend(loc='best',title='figure 1 legend') #去掉图例边框

2.legend面向对象命令

(1)获取并设置legend图例       

plt.legend(loc=0, numpoints=1)
leg = plt.gca().get_legend() #或leg=ax.get_legend()
ltext = leg.get_texts()
plt.setp(ltext, fontsize=12,fontweight='bold')

(2)设置图例

legend = ax.legend((rectsTest1, rectsTest2, rectsTest3), ('test1', 'test2', 'test3'))
legend = ax.legend(loc='upper center', shadow=True, fontsize='x-large')
legend.get_frame().set_facecolor('red') #设置图例legend背景为红色
frame = legend.get_frame()
frame.set_alpha(1)
frame.set_facecolor('none') #设置图例legend背景透明

(3)移除图例

ax1.legend_.remove() ##移除子图ax1中的图例
ax2.legend_.remove() ##移除子图ax2中的图例
ax3.legend_.remove() ##移除子图ax3中的图例

3.案例:设置图例legend到图形边界外

#主要是bbox_to_anchor的使用
box = ax1.get_position()
ax1.set_position([box.x0, box.y0, box.width , box.height* 0.8])
ax1.legend(loc='center', bbox_to_anchor=(0.5, 1.2),ncol=3)

4.案例:显示多图例legend

import matplotlib.pyplot as plt
import numpy as np
x = np.random.uniform(-1, 1, 4)
y = np.random.uniform(-1, 1, 4)
p1, = plt.plot([1,2,3])
p2, = plt.plot([3,2,1])
l1 = plt.legend([p2, p1], ["line 2", "line 1"], loc='upper left')

p3 = plt.scatter(x[0:2], y[0:2], marker = 'D', color='r')
p4 = plt.scatter(x[2:], y[2:], marker = 'D', color='g')
# This removes l1 from the axes.
plt.legend([p3, p4], ['label', 'label1'], loc='lower right', scatterpoints=1)
# Add l1 as a separate artist to the axes
plt.gca().add_artist(l1)

import matplotlib.pyplot as plt
line1, = plt.plot([1,2,3], label="Line 1", linestyle='--')
line2, = plt.plot([3,2,1], label="Line 2", linewidth=4)
# 为第一个线条创建图例
first_legend = plt.legend(handles=[line1], loc=1)
# 手动将图例添加到当前轴域
ax = plt.gca().add_artist(first_legend)
# 为第二个线条创建另一个图例
plt.legend(handles=[line2], loc=4)
plt.show()

到此这篇关于matplotlib图例legend语法及设置的方法的文章就介绍到这了,更多相关matplotlib legend内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python matplotlib画图时图例说明(legend)放到图像外侧详解

    用python的matplotlib画图时,往往需要加图例说明.如果不设置任何参数,默认是加到图像的内侧的最佳位置. import matplotlib.pyplot as plt import numpy as np x = np.arange(10) fig = plt.figure() ax = plt.subplot(111) for i in xrange(5): ax.plot(x, i * x, label='$y = %ix$' % i) plt.legend() plt.sho

  • matplotlib设置legend图例代码示例

    本文主要是关于matplotlib的一些基本用法. Demo import matplotlib.pyplot as plt import numpy as np # 绘制普通图像 x = np.linspace(-1, 1, 50) y1 = 2 * x + 1 y2 = x**2 plt.figure() # 在绘制时设置lable, 逗号是必须的 l1, = plt.plot(x, y1, label = 'line') l2, = plt.plot(x, y2, label = 'par

  • matplotlib中legend位置调整解析

    在画一些曲线图(linecharts)时,常常会出现多条曲线同时画在一张图上面,这时候就需要对不同的曲线进行不同的标注,以使读者能够清晰地知道每条曲线代表的含义.当你画很少的几条曲线时,这时画图命令中自动产生的legend能够基本满足你的需要,此时,你不需要做什么:但当你将很多个曲线画在一张图上时,自动产生的legend矩形框往往会覆盖住已经画出来的曲线,很不美观,这时你就需要写专门的代码对legend的位置进行精确的控制,而不能再依靠系统帮你自动控制了. 本文所讲的就是要解决如何在一张图上画多

  • 关于matplotlib-legend 位置属性 loc 使用说明

    在使用matplotlib画图时,少不了对性能图形做出一些说明和补充.一般情况下,loc属性设置为'best'就足够应付了 plt.legend(handles = [l1, l2,], labels = ['a', 'b'], loc = 'best') 或直接loc = 0 plt.legend(handles = [l1, l2,], labels = ['a', 'b'], loc = 0) 除'best',另外loc属性有: 'upper right', 'upper left', '

  • matplotlib图例legend语法及设置的方法

    1.图例legend基础语法及用法 legend语法参数如下: matplotlib.pyplot.legend(*args, **kwargs) Keyword Description loc Location code string, or tuple (see below).图例所有figure位置 prop the font property字体参数 fontsize the font size (used only if prop is not specified) markersca

  • R语言ggplot2设置图例(legend)的操作大全

    目录 基本箱线图(带有图例) 移除图例 修改图例的内容 颠倒图例的顺序 隐藏图例标题 修改图例中的标签 修改data.frame的factor 修改标题和标签的显示 修改图例的框架 设置图例的位置 隐藏斜线 总结 本文在 http://www.cookbook-r.com/Graphs/Scatterplots_(ggplot2)/ 的基础上加入了自己的理解 图例用来解释图中的各种含义,比如颜色,形状,大小等等, 在ggplot2中aes中的参数(x, y 除外)基本都会生成图例来解释图形, 比

  • python可视化plotly 图例(legend)设置

    目录 一.图例(legend) 二.update_layout(legend={}) 相关参数及示例 一.图例(legend) import plotly.io as pio import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd import numpy as np # 设置plotly默认主题 pio.

  • Matplotlib 绘制饼图解决文字重叠的方法

    在使用Matplotlib 绘制饼图的时候有些时候一些数据的比列太小在饼图呈现的效果不明显 很容易被覆盖,为了解决这个问题以下就是我个人的心得. [未解决之前呈现的效果] 可以看到这个饼状图其他和硕士这2个部分占比很小而且比例相互覆盖,这让人看起来不舒服,所以针对这个问题我们可以调整下字体大小以及布局大小. 1.设置字体的大小 patches,l_text,p_text=plt.pie(values, spaces, labels, colors, '%.1f%%', shadow=True,

  • Python matplotlib图例放在外侧保存时显示不完整问题解决

    上次说到的,使用如下代码保存矢量图时,放在外侧的图例往往显示不完整: import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() x1 = np.random.uniform(-10, 10, size=20) x2 = np.random.uniform(-10, 10, size=20) #print(x1) #print(x2) number = [] x11 = [] x12 = [] for i

  • pycharm使用matplotlib.pyplot不显示图形的解决方法

    如下案例,可以正常保存图像,但是plt.show()不能正常显示图像,这里是使用pandas模块读取csv文件: # coding=utf-8 import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('ccpoints.csv', header=0) plt.scatter(data.x, data.y, c="red", marker='o', label='ccpoints') plt.xlabe

  • Python基于Matplotlib库简单绘制折线图的方法示例

    本文实例讲述了Python基于Matplotlib库简单绘制折线图的方法.分享给大家供大家参考,具体如下: Matplotlib画折线图,有一些离散点,想看看这些点的变动趋势: import matplotlib.pyplot as plt x1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] y1=[30,31,31,32,33,35,35,40,47,62,99,186,480] x2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1

  • Python使用Matplotlib实现雨点图动画效果的方法

    本文实例讲述了Python使用Matplotlib实现雨点图动画效果的方法.分享给大家供大家参考,具体如下: 关键点 win10安装ffmpeg animation函数使用 update函数 win10安装ffmpeg 因为最后要将动画图保存为.mp4格式,要用到ffmpeg,去官网下载,我az下载的是windows64bit static版本的,下载后解压到软件安装常用路径,并将ffmpeg路径添加到环境变量(这个方法在最后没用,但还是添加一下) animationa函数 准确来说是anima

  • Python matplotlib的使用并自定义colormap的方法

    0.前言 添加colormap的对象是灰度图,可以变成热量图,从而更加明显的发现一些规律,适用于一些雷达图像等 from PIL import Image # 将彩色图片转换成黑白图片 im=Image.open("./pic.jpg").convert('L') # 保存图片 im.save("image.jpg") 1.从灰色图片中读取数据,转换成colormap图 import matplotlib.pyplot as plt import matplotli

  • 在echarts中图例legend和坐标系grid实现左右布局实例

    1.效果图 2.实现方法 将图例legend纵向排列(orient: 'vertical'),宽度给150(width: 150),坐标系grid左侧距离200(left: 200),中间有50的边距 3.代码展示 grid: { left: 200 }, legend: { x: 'left', data: ['送风温度', '混风温度', '冷冻水送水温度', '冷冻水回水温度', '热水送水温度', '热水回水温度', '送风温度设定点', '风机速度','风机速度反馈','风阀开度'],

随机推荐