我正在像这样在 Matplotlib 中创建一个图形:
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')
我想为图形标题和轴标签指定字体大小。我需要这三个字体大小不同,因此设置全局字体大小 (mpl.rcParams['font.size']=x
) 不是我想要的。如何分别设置图形标题和轴标签的字体大小?
mpl.rcParams['font.size'] = 20
并尝试将值更改为 10 和 14。首先我发现除非我将 mpl
更改为 plt
,否则我会出错。该更改清除了错误,但代码行对我的标题或标签没有影响。确定这种语法是正确的?
mpl
命令时是否使用了另一条导入行?
处理 label
、title
等文本的函数接受与 matplotlib.text.Text
相同的参数。对于字体大小,您可以使用 size/fontsize
:
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')
对于全局设置 title
和 label
大小,mpl.rcParams
包含 axes.titlesize
和 axes.labelsize
。 (从页面):
axes.titlesize : large # fontsize of the axes title
axes.labelsize : medium # fontsize of the x any y labels
(据我所知,没有办法分别设置 x
和 y
标签大小。)
而且我看到 axes.titlesize
不会影响 suptitle
。我想,你需要手动设置。
您也可以通过 rcParams 字典全局执行此操作:
import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
pylab.rcParams.update(params)
'x-large'
之外还有哪些尺寸?
pylab.rcParams.keys()
查看完整的参数列表。
ax.set_title('some title', fontsize=15)
,ax.set_xlabel('some xlabel', fontsize=12)
?似乎 rcParams
只接受字符串。
'axes.labelsize': 32,
如果您更习惯于使用 ax
对象进行绘图,您可能会发现 ax.xaxis.label.set_size()
更容易记住,或者至少更容易在 ipython 终端中使用选项卡找到。之后好像需要重绘操作才能看到效果。例如:
import matplotlib.pyplot as plt
# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)
# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium') # relative to plt.rcParams['font.size']
# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()
我不知道在创建后设置字幕大小的类似方法。
fig.suptitle('test title', fontsize = 20)
似乎有效。 ax.set_xlabel('xlabel', fontsize = 20)' also works, in which case we can do away with
ax.xaxis.label.set_size(20)`。
ax.xaxis.label.set_size()
很有用。
plt.xlabel()
与 ax.set_xlabel()
),它们是等价的,但需要注意的是 plt.*
函数适用于 current i> 轴/图。因此,如果您设置了一个具有多个轴的图形,您可能需要使用像 ax1.set_xlabel()
这样的显式调用来避免混淆。
为了只修改标题的字体(而不是轴的字体),我使用了这个:
import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})
fontdict 接受来自 matplotlib.text.Text 的所有 kwarg。
fontdict
。它确实有效,但您也可以使用:ax.set_title("My Title", fontsize=18, fontwieght="medium")
。这也适用于 ax2.set_xticklabels
等。
根据官方指南,不再推荐使用 pylab。 matplotlib.pyplot 应该直接使用。
应该通过 rcParams
全局设置字体大小
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.titlesize'] = 16
# or
params = {'axes.labelsize': 16,
'axes.titlesize': 16}
plt.rcParams.update(params)
# or
import matplotlib as mpl
mpl.rc('axes', labelsize=16, titlesize=16)
# or
axes = {'labelsize': 16,
'titlesize': 16}
mpl.rc('axes', **axes)
可以使用恢复默认值
plt.rcParams.update(plt.rcParamsDefault)
您也可以通过在 matplotlib configuration directory 下的 stylelib
目录中创建一个 style sheet 来执行此操作(您可以从 matplotlib.get_configdir()
获取您的配置目录)。样式表格式为
axes.labelsize: 16
axes.titlesize: 16
如果您在 /path/to/mpl_configdir/stylelib/mystyle.mplstyle
有一个样式表,那么您可以通过
plt.style.use('mystyle')
# or, for a single section
with plt.style.context('mystyle'):
# ...
您还可以创建(或修改)共享格式的 matplotlibrc file
axes.labelsize = 16
axes.titlesize = 16
根据您修改的 matplotlibrc 文件,这些更改将仅用于当前工作目录、所有没有有 matplotlibrc 文件的工作目录,或所有没有<< /strong> 有一个 matplotlibrc 文件,并且没有指定其他 matplotlibrc 文件。有关更多详细信息,请参阅自定义 matplotlib 页面的 this section。
可以通过 plt.rcParams.keys()
检索 rcParams
键的完整列表,但要调整您拥有的字体大小(斜体引自 here)
axes.labelsize - x 和 y 标签的字体大小
axes.titlesize - 坐标区标题的字体大小
figure.titlesize - 图标题的大小 (Figure.suptitle())
xtick.labelsize - 刻度标签的字体大小
ytick.labelsize - 刻度标签的字体大小
legend.fontsize - 图例的字体大小 (plt.legend(), fig.legend())
legend.title_fontsize - 图例标题的字体大小,无设置为与默认轴相同。有关用法示例,请参见此答案。
所有这些都接受字符串大小 {'xx-small', 'x-small', 'smaller', 'small', 'medium', 'large', 'larger', 'x-large', 'xxlarge'}
或 pt
中的 float
。字符串大小是相对于由指定的默认字体大小定义的
font.size - 文本的默认字体大小,以 pts 为单位。 10 pt 是标准值
此外,可以通过以下方式指定权重(尽管仅针对其出现的默认值)
font.weight - text.Text 使用的字体的默认粗细。接受 {100, 200, 300, 400, 500, 600, 700, 800, 900} 或“正常”(400)、“粗体”(700)、“较轻”和“粗体”(相对于当前重量) )。
如果您没有显式创建图形和轴对象,则可以在使用 fontdict
参数创建标题时设置标题字体大小。
当您使用 fontsize
参数创建 x 和 y 标签时,您可以分别设置 x 和 y 标签字体大小。
例如:
plt.title('Car Prices are Increasing', fontdict={'fontsize':20})
plt.xlabel('Year', fontsize=18)
plt.ylabel('Price', fontsize=16)
也适用于 seaborn 和 pandas 绘图(当 Matplotlib 是后端时)!
其他人已经提供了如何更改标题大小的答案,但是对于轴刻度标签大小,您也可以使用set_tick_params方法。
例如,要使 x 轴刻度标签尺寸变小:
ax.xaxis.set_tick_params(labelsize='small')
或者,使 y 轴刻度标签变大:
ax.yaxis.set_tick_params(labelsize='large')
您还可以输入 labelsize
作为浮点数,或以下任何字符串选项:'xx-small'、'x-small'、'small'、'medium'、'large'、'x-large'、或“xx 大”。
更改字体大小的另一种解决方案是更改填充。当 Python 保存您的 PNG 时,您可以使用打开的对话框更改布局。轴之间的间距,如果您愿意,可以在此阶段更改填充。
将 right_ax
放在 set_ylabel()
之前
ax.right_ax.set_ylabel('AB scale')
图书馆
将 numpy 导入为 np
将 matplotlib.pyplot 导入为 plt
创建数据集
高度 = [3, 12, 5, 18, 45]
条形=('A','B','C','D','E')
x_pos = np.arange(len(bars))
创建条形图并选择颜色
plt.bar(x_pos, 高度, 颜色 = (0.5,0.1,0.5,0.6))
添加标题和轴名称
plt.title('我的标题')
plt.xlabel('类别')
plt.ylabel('值')
在 x 轴上创建名称
plt.xticks(x_pos, 条形图)
显示情节
plt.show()
7(最佳解决方案)
from numpy import*
import matplotlib.pyplot as plt
X = linspace(-pi, pi, 1000)
class Crtaj:
def nacrtaj(self,x,y):
self.x=x
self.y=y
return plt.plot (x,y,"om")
def oznaci(self):
return plt.xlabel("x-os"), plt.ylabel("y-os"), plt.grid(b=True)
6(稍微差一点的解决方案)
from numpy import*
M = array([[3,2,3],[1,2,6]])
class AriSred(object):
def __init__(self,m):
self.m=m
def srednja(self):
redovi = len(M)
stupci = len (M[0])
lista=[]
a=0
suma=0
while a<stupci:
for i in range (0,redovi):
suma=suma+ M[i,a]
lista.append(suma)
a=a+1
suma=0
b=array(lista)
b=b/redovi
return b
OBJ = AriSred(M)
sr = OBJ.srednja()
不定期副业成功案例分享
mpl.rcParams
。我已经编辑了我的答案。plt.rcParams.update({'axes.titlesize': 'small'})
rcParams
链接中,除了axes.titlesize
之外,还使用figure.titlesize
。python -c 'import matplotlib as mpl; print(mpl.__version__); print("figure.titlesize" in mpl.rcParams.keys())'
。结果是1.5.1
、True
。 1)你使用的是什么版本的matplotlib?什么版本的 Python? 2) 它可能是一个错误,由于某种原因它在 Py2 中接受str
但不接受unicode
?