一、ax.legend参数
在matplotlib中,ax.legend()函数主要用于为图形添加图例。在传递参数时,我们可以使用一系列关键字参数来定制图例的位置,大小,字体等属性。以下是ax.legend()支持的常用参数:
参数名 类型 说明 loc string 指定图例的位置 bbox_to_anchor tuple 指定图例的锚点(外部边界或图表顶部左上) ncol int 指定图例的列数 fontsize int 指定图例的字体大小 title string 图例的标题 frame_on bool 是否显示图例的边框 shadow bool 是否显示图例的阴影 fancybox bool 是否为图例的边框添加圆角 framealpha float 图例的边框透明度
其中,loc参数可以指定图例在哪个位置出现。它可以采用一个字符串,表示需要显示图例的位置,如’upper right’、’lower left’等。另外,loc参数也可以接收一个长度为2的元组来指定图例的位置。例如,(0.5, 0.5)表示图例的位置位于图形区域的中心。
二、ax.legend设置边框粗细
ax.legend()函数中的frame_linewidth参数用于设置图例边框的粗细程度。frame_linewidth参数需要指定一个浮点数来表示边框的粗细程度,例如:
import matplotlib.pyplot as plt
plt.style.use('ggplot')
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [2, 4, 6], label='line 1')
ax.plot([1, 2, 3], [1, 3, 5], label='line 2')
legend = ax.legend(loc='upper center', frame_linewidth=2)在上述代码中,我们将frame_linewidth参数设置为2,表示图例边框的粗细为2个单位。图例将会位于图表的中上方。
三、ax.legend设置边框颜色
在matplotlib中,ax.legend()函数中的frame_color参数用于指定图例边框的颜色。
import matplotlib.pyplot as plt
plt.style.use('ggplot')
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [2, 4, 6], label='line 1')
ax.plot([1, 2, 3], [1, 3, 5], label='line 2')
legend = ax.legend(loc='upper center', frame_color='red')上述代码中,我们将frame_color参数设置为’red’,表示图例边框的颜色为红色。图例将会位于图表的中上方。
四、ax.legend的字体大小
在matplotlib中,ax.legend()函数中的fontsize参数用于指定图例的字体大小。fontsize参数需要指定一个整数来表示字体的大小,例如:
import matplotlib.pyplot as plt
plt.style.use('ggplot')
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [2, 4, 6], label='line 1')
ax.plot([1, 2, 3], [1, 3, 5], label='line 2')
legend = ax.legend(loc='upper center', fontsize=14)在上述代码中,我们将fontsize参数设置为14,表示图例的字体大小为14个单位。图例将会位于图表的中上方。
五、ax.legend实例
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Data
x = np.linspace(-10, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Plot
fig, ax = plt.subplots(figsize=(10,6))
ax.plot(x, y1, label='sin(x)', linewidth=2)
ax.plot(x, y2, label='cos(x)', linewidth=2)
# Legend
legend = ax.legend(loc='upper center', shadow=True, fontsize=16)
legend.get_frame().set_facecolor('#FFFFFF') # 设置图例边框颜色
plt.setp(legend.get_lines(), linewidth=4) # 设置标签线宽
plt.show()上述代码中,我们生成了两个曲线数据y1和y2,并分别用ax.plot()将它们绘制到了图形上。随后,我们通过ax.legend()函数为该图形添加了一个图例。图例的位置位于图表顶部中心,阴影效果开启,字体大小为16。
在图例的生成后,我们对其进行了一系列自定义设置:设置图例边框为白色,标签线宽为4。
最终,我们调用plt.show()函数显示该图形。图形的结果如下所示:
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/157814.html
微信扫一扫
支付宝扫一扫