2010-10-10 260 views
259

如何更改matplotlib圖上所有元素(蜱,標籤,標題)的字體大小?如何更改matplotlib圖上的字體大小

我知道如何更改刻度標籤尺寸,這與做:

import matplotlib 
matplotlib.rc('xtick', labelsize=20) 
matplotlib.rc('ytick', labelsize=20) 

但如何改變一個休息?

回答

291

matplotlib documentation

font = {'family' : 'normal', 
     'weight' : 'bold', 
     'size' : 22} 

matplotlib.rc('font', **font) 

這設定的所有項目的字體由kwargs指定的字體對象,font

或者,您也可以使用rcParamsupdate方法在this answer建議:

matplotlib.rcParams.update({'font.size': 22}) 

您可以找到Customizing matplotlib page可用屬性的完整列表。

+2

不錯的,只是它覆蓋在它發現任何字號屬性的方式è_é – yota 2014-09-25 11:56:03

+1

我在哪裏可以找到像'「family'','」 weight''等元素更多的選擇? – haccks 2015-06-11 09:26:09

+0

@haccks我在答案中添加了自定義matplotlib頁面的鏈接。 – 2015-06-11 16:45:08

136
matplotlib.rcParams.update({'font.size': 22}) 
128

如果要更改已創建的只是一個特定的情節字號,試試這個:

import matplotlib.pyplot as plt 

ax = plt.subplot(111, xlabel='x', ylabel='y', title='title') 
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + 
      ax.get_xticklabels() + ax.get_yticklabels()): 
    item.set_fontsize(20) 
+0

我的目的是讓xy標籤的字體,標記和標題具有不同的大小,這個修改後的版本對我很有效 – 2017-02-13 05:27:53

+2

要獲得傳說,請使用ax.legend()。get_texts()在Matplotlib 1.4上測試 – 2017-09-11 04:19:37

50

更新:一看便知的底部稍微好一點的辦法做到這一點。
更新#2:我也想出了更改圖例標題字體。
更新#3:有一個bug in Matplotlib 2.0.0導致對數軸的刻度標籤恢復爲默認字體。應該在2.0.1中解決,但我在答案的第二部分中包含了解決方法。

這個答案適用於所有嘗試更改所有字體的人,包括圖例,以及任何嘗試爲每種東西使用不同字體和大小的人。它不使用rc(這似乎不適合我)。這是相當麻煩的,但我無法親自處理任何其他方法。它基本上將ryggyr的答案與SO上的其他答案結合在一起。

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.font_manager as font_manager 

# Set the font dictionaries (for plot title and axis titles) 
title_font = {'fontname':'Arial', 'size':'16', 'color':'black', 'weight':'normal', 
       'verticalalignment':'bottom'} # Bottom vertical alignment for more space 
axis_font = {'fontname':'Arial', 'size':'14'} 

# Set the font properties (for use in legend) 
font_path = 'C:\Windows\Fonts\Arial.ttf' 
font_prop = font_manager.FontProperties(fname=font_path, size=14) 

ax = plt.subplot() # Defines ax variable by creating an empty plot 

# Set the tick labels font 
for label in (ax.get_xticklabels() + ax.get_yticklabels()): 
    label.set_fontname('Arial') 
    label.set_fontsize(13) 

x = np.linspace(0, 10) 
y = x + np.random.normal(x) # Just simulates some data 

plt.plot(x, y, 'b+', label='Data points') 
plt.xlabel("x axis", **axis_font) 
plt.ylabel("y axis", **axis_font) 
plt.title("Misc graph", **title_font) 
plt.legend(loc='lower right', prop=font_prop, numpoints=1) 
plt.text(0, 0, "Misc text", **title_font) 
plt.show() 

這種方法的好處是,通過有幾個字體庫,你可以選擇不同的字體/尺寸/重量/對於各種頭銜的顏色,選擇刻度標籤的字體,並選擇字體傳奇,都是獨立的。


UPDATE:

我已經制定了一個稍微不同的,更簡潔的辦法,摒棄了字體庫,並允許你的系統上的任何字體,甚至雜項文件字體。要爲每個事物分別設置字體,只需編寫更多類似於變量的font_pathfont_prop

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.font_manager as font_manager 
import matplotlib.ticker 
# Workaround for Matplotlib 2.0.0 log axes bug https://github.com/matplotlib/matplotlib/issues/8017 : 
matplotlib.ticker._mathdefault = lambda x: '\\mathdefault{%s}'%x 

# Set the font properties (can use more variables for more fonts) 
font_path = 'C:\Windows\Fonts\AGaramondPro-Regular.otf' 
font_prop = font_manager.FontProperties(fname=font_path, size=14) 

ax = plt.subplot() # Defines ax variable by creating an empty plot 

# Define the data to be plotted 
x = np.linspace(0, 10) 
y = x + np.random.normal(x) 
plt.plot(x, y, 'b+', label='Data points') 

for label in (ax.get_xticklabels() + ax.get_yticklabels()): 
    label.set_fontproperties(font_prop) 
    label.set_fontsize(13) # Size here overrides font_prop 

plt.title("Exponentially decaying oscillations", fontproperties=font_prop, 
      size=16, verticalalignment='bottom') # Size here overrides font_prop 
plt.xlabel("Time", fontproperties=font_prop) 
plt.ylabel("Amplitude", fontproperties=font_prop) 
plt.text(0, 0, "Misc text", fontproperties=font_prop) 

lgd = plt.legend(loc='lower right', prop=font_prop) # NB different 'prop' argument for legend 
lgd.set_title("Legend", prop=font_prop) 

plt.show() 

希望這是一個全面的答案

4

基於以上的東西:

import matplotlib.pyplot as plt 
import matplotlib.font_manager as fm 

fontPath = "/usr/share/fonts/abc.ttf" 
font = fm.FontProperties(fname=fontPath, size=10) 
font2 = fm.FontProperties(fname=fontPath, size=24) 

fig = plt.figure(figsize=(32, 24)) 
fig.text(0.5, 0.93, "This is my Title", horizontalalignment='center', fontproperties=font2) 

plot = fig.add_subplot(1, 1, 1) 

plot.xaxis.get_label().set_fontproperties(font) 
plot.yaxis.get_label().set_fontproperties(font) 
plot.legend(loc='upper right', prop=font) 

for label in (plot.get_xticklabels() + plot.get_yticklabels()): 
    label.set_fontproperties(font) 
12

這裏是一個完全不同辦法,工作出奇地好來改變字體大小:

更改數字大小

我通常使用這樣的代碼:

import matplotlib.pyplot as plt 
import numpy as np 
[enter image description here][1]fig = plt.figure(figsize=(4,3)) 
ax = fig.add_subplot(111) 
x = np.linspace(0,6.28,21) 
ax.plot(x, np.sin(x), '-^', label="1 Hz") 
ax.set_title("Oscillator Output") 
ax.set_xlabel("Time (s)") 
ax.set_ylabel("Output (V)") 
ax.grid(True) 
ax.legend(loc=1) 
fig.savefig('Basic.png', dpi=300) 

你做圖的大小,較大字體是相對於情節。這也提高了標記。注意我也設置了dpi或每英寸點數。我從發佈AMTA(美國模特老師)論壇中瞭解到這一點。 例子:Figure from above code

+0

哇,這對我很好,謝謝你分享這些信息。 – muammar 2017-08-23 19:00:19

68

如果你像我一樣是個控制狂,你可能要明確設置你的所有字體大小:

import matplotlib.pyplot as plt 

SMALL_SIZE = 8 
MEDIUM_SIZE = 10 
BIGGER_SIZE = 12 

plt.rc('font', size=SMALL_SIZE)   # controls default text sizes 
plt.rc('axes', titlesize=SMALL_SIZE)  # fontsize of the axes title 
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels 
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels 
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels 
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize 
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title 

請注意,您還可以設置大小呼籲matplotlibrc方法:

import matplotlib 

SMALL_SIZE = 8 
matplotlib.rc('font', size=SMALL_SIZE) 
matplotlib.rc('axes', titlesize=SMALL_SIZE) 

# and so on ... 
+2

我嘗試了很多答案。至少在Jupyter筆記本中,這個看起來最好。只需在頂部複製上面的塊並自定義三種字體大小的常量。 – fviktor 2017-09-13 18:48:07

+0

同意fvitkor,這是最好的答案! – SeF 2018-01-08 18:23:36

2

我完全Huster教授同意進行最簡單的方法是改變數字,這允許保持默認字體的大小。在將圖保存爲PDF時,我只需要使用bbox_inches選項對此進行補充,因爲軸標籤已被剪切。

import matplotlib.pyplot as plt 
plt.figure(figsize=(4,3)) 
plt.savefig('Basic.pdf', bbox_inches='tight') 
0

這是Marius Retegan answer的擴展。您可以使用所有修改創建單獨的JSON文件,並使用rcParams.update加載它。此更改僅適用於當前腳本。所以

import json 
from matplotlib import pyplot as plt, rcParams 

s = json.load(open("example_file.json") 
rcParams.update(s) 

並將此'example_file.json'保存在同一個文件夾中。

{ 
    "lines.linewidth": 2.0, 
    "axes.edgecolor": "#bcbcbc", 
    "patch.linewidth": 0.5, 
    "legend.fancybox": true, 
    "axes.color_cycle": [ 
    "#348ABD", 
    "#A60628", 
    "#7A68A6", 
    "#467821", 
    "#CF4457", 
    "#188487", 
    "#E24A33" 
    ], 
    "axes.facecolor": "#eeeeee", 
    "axes.labelsize": "large", 
    "axes.grid": true, 
    "patch.edgecolor": "#eeeeee", 
    "axes.titlesize": "x-large", 
    "svg.fonttype": "path", 
    "examples.directory": "" 
}