matplotlib中如何将图例位置放在绘图区外
bbox_to_anchor
参数#
可以通过bbox_to_anchor
参数将图例放置在坐标系外。bbox
表示容纳图例的边界框-bounding box
plt.legend(bbox_to_anchor=(x0, y0, width, height), loc=)
width
和height
是图例框的宽度和高度,而(x0, y0)
是边界框loc
的坐标。
边界框的坐标是相对于坐标系的位置,(0,0)是坐标系的左下角,(1,1)是坐标系的右上角
loc参数可选值(默认为0):
int | str |
---|---|
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 |
示例#
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label="sin(x)")
plt.plot(x, np.cos(x), label="cos(x)")
plt.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
plt.tight_layout()
plt.show()
如果未调用tight_layout(),保存的图片将会显示不完整
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label="sin(x)")
plt.plot(x, np.cos(x), label="cos(x)")
plt.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
# plt.show()
# plt.tight_layout()
plt.savefig('0.png')
使用bbox_extra_artists
和 bbox_inches
参数,防止图像保存时被裁剪#
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label="sin(x)")
plt.plot(x, np.cos(x), label="cos(x)")
lg = plt.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
plt.savefig('example.png',
dpi=300,
format='png',
bbox_extra_artists=(lg,),
bbox_inches='tight')
bbox_extra_artists
指定 Artist
的列表,在计算bbox
最小边界时会将这些Artist
考虑在内。
如果將 bbox_inches
设定为 tight
,它将计算出图中的紧凑型 bbox
。
转载自:原文链接
分类:
数据可视化
标签:
matplotlib
, 数据可视化
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App