使用matplotlib绘制图标时,图例plt.legend()的使用

plt.legend(loc=3, bbox_to_anchor=(-0.12, -0.12))

图例通过loc,bbox_to_anchor设置位置

参数1:loc()

此参数用来确定图里的一个大概位置
upper right (1)
upper left (2)
lower left (3)
lower right (4)
center left (6)
center right (7)
lower center(8)
upper center(9)

参数2:bbox_to_anchor(num1,num2)

用来细微调节图例的位置
num1 用于控制 legend 的左右移动,值越大,越向右移动;
num2 用于控制 legend 的上下移动,值越大,越向上移动。

案例

1.无参数

"""
    绘制饼图
"""
import numpy as np
import matplotlib.pyplot as plt

# 构建窗口
plt.figure('Computer language', facecolor='lightgray')
# 设置标题
plt.title("Computer language's popularity", fontdict={
    
    'fontsize': 24, 'color': 'r'})
# 绘制饼图
x = np.array([23, 30, 13, 24, 10])
explode = [0.05, 0.01, 0.01, 0.01, 0.01]
language_class = ['python', 'java', 'hadoop', 'C++', 'C']
color = ['r', 'blue', 'yellow', 'orange', 'white']
plt.pie(x=x, explode=explode, labels=language_class,
        colors=color, autopct='%1.1f%%', shadow=True)
# 设置图例
plt.legend()
plt.axis('equal')
# 展示
plt.show()

效果展示:
在这里插入图片描述

2.添加参数

plt.legend(loc=3, bbox_to_anchor=(-0.12, -0.12))

效果展示:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_51489557/article/details/130065239