[英]How do I set the figure title and axes labels font size in Matplotlib?
我正在像這樣在 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
)不是我想要的。 如何分別設置圖形標題和軸標簽的字體大小?
處理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)
如果您更習慣於使用ax
對象進行繪圖,您可能會發現ax.xaxis.label.set_size()
更容易記住,或者至少更容易在 ipython 終端中使用 tab 找到。 之后好像需要重繪操作才能看到效果。 例如:
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()
我不知道在創建后設置字幕大小的類似方法。
為了只修改標題的字體(而不是軸的字體),我使用了這個:
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的所有 kwargs。
根據官方指南,不再推薦使用
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 配置目錄下的stylelib
目錄中創建樣式表來做到這一點(您可以從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 文件
axes.labelsize = 16
axes.titlesize = 16
根據您修改的 matplotlibrc 文件,這些更改將僅用於當前工作目錄、所有沒有matplotlibrc 文件的工作目錄,或所有沒有matplotlibrc 文件且沒有其他 matplotlibrc 文件的工作目錄被指定。 有關更多詳細信息,請參閱自定義 matplotlib 頁面的這一部分。
可以通過plt.rcParams.keys()
檢索rcParams
鍵的完整列表,但要調整字體大小( 此處引用的斜體字)
axes.labelsize
- x 和 y 標簽的字體大小axes.titlesize
-坐標區標題的字體大小figure.titlesize
-圖標題的大小( Figure.suptitle()
)xtick.labelsize
-刻度標簽的字體大小ytick.labelsize
-刻度標簽的字體大小legend.fontsize
- 圖例的字體大小( plt.legend()
, fig.legend()
)legend.title_fontsize
- 圖例標題的字體大小, None
設置為與默認軸相同。 有關用法示例,請參見此答案。 所有這些都接受字符串大小{'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}
或'normal'
(400), 'bold'
(700), 'lighter'
和'bolder'
(相對於當前重量)。如果您沒有顯式創建圖形和軸對象,則可以在使用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('值')
plt.xticks(x_pos, 條形圖)
plt.show()
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)
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.