Matplotlib 中如何更改图例字体大小

您所在的位置:网站首页 怎么修改python字体大小 Matplotlib 中如何更改图例字体大小

Matplotlib 中如何更改图例字体大小

2023-03-24 18:23| 来源: 网络整理| 查看: 265

rcParams 方法指定字体大小 plt.legend(fontsize= ) 指定图例字体大小的方法 图例中的 prop 属性

我们有不同的方法来设置 Matplotlib 中图例中文本的字体大小。

rcParams 方法指定字体大小

rcParams 是处理 Matplotlib 属性和默认样式的字典。

1. plt.rc('legend', fontsize= ) 方法

fontsize 可以是单位为 points 的整数,也可以是表征大小的字符串,例如

xx--small x-small small medium large x-large xx-large plt.rc('legend', fontsize=16) plt.rc('legend', fontsize='medium')

2. plt.rcparams.update() 方法 import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) plt.plot(x, np.sin(x), label="sin(x)") params = {'legend.fontsize': 16, 'legend.handlelength': 3} plt.rcParams.update(params) plt.legend(loc='upper left') plt.tight_layout() plt.show()

legend.fontsize 指定图例字体大小,而 legend.handlelength 指定图例句柄长度,以字体大小为单位。

plt.rcParams.update(params) 用上面定义的字典 params 来更新 Matplotlib 属性和样式。

或者,你可以通过将键值放在括号 [] 中来更新 rcParams 字典,

plt.rcParams['legend.fontsize'] = 16 plt.rcParams['legend.handlelength'] = 16 plt.legend(fontsize= ) 指定图例字体大小的方法

plt.legend(fontsize=) 可以在创建每个图例时指定图例字体大小。

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.legend(fontsize=16, loc='upper right') plt.show() 图例中的 prop 属性

图例中的 prop 属性可以设置图例的单个字体大小。prop 是来自 matplotlib.font_manager.FontProperties 中的关键字构成的字典。

plt.legend(prop={'size': 16})

例:

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.legend(prop={'size':16}, loc='best') plt.show()


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3