2010-10-10 42 views
259

¿Cómo se puede cambiar el tamaño de fuente de todos los elementos (ticks, labels, title) en un diagrama matplotlib?Cómo cambiar el tamaño de fuente en un diagrama matplotlib

Sé cómo cambiar los tamaños de etiquetas garrapata, esto se hace con:

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

Pero, ¿cómo cambiar el resto?

Respuesta

291

Desde el matplotlib documentation,

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

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

Esto establece la fuente de todos los artículos a la fuente especificada por los kwargs objeto, font.

Como alternativa, también se puede utilizar el método rcParamsupdate como se sugiere en this answer:

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

Puede encontrar una lista completa de propiedades disponibles en el Customizing matplotlib page.

+2

agradable, excepto que anula cualquier propiedad tamaño de fuente que se encuentra en su camino e_e – yota

+1

¿Dónde puedo encontrar más opciones para los elementos como ' 'family'','' weight'', etc.? – haccks

+0

@haccks Agregué un enlace a la página de matplotlib de personalización en la respuesta. –

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

Si desea cambiar el tamaño de fuente por sólo una parcela específica que ya ha sido creado, intente esto:

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

Mi propósito era que la fuente de las etiquetas xy, las marcas y los títulos fueran de diferentes tamaños. Una versión modificada de esto me funcionó tan bien. –

+2

Para obtener las leyendas, también use ax.legend(). Get_texts() . Probado en Matplotlib 1.4. –

50

Actualización: Ver la parte inferior de la respuesta de una manera un poco mejor de hacerlo
Actualización n. ° 2: He descubierto el cambio de las fuentes del título de la leyenda también.
Actualización n. ° 3: Hay un bug in Matplotlib 2.0.0 que está haciendo que las etiquetas de tilde para los ejes logarítmicos reviertan a la fuente predeterminada. Debe arreglarse en 2.0.1 pero he incluido la solución en la segunda parte de la respuesta.

Esta respuesta es para cualquier persona que intente cambiar todas las fuentes, incluida la leyenda, y para cualquiera que intente usar diferentes fuentes y tamaños para cada cosa. No usa rc (que no parece funcionar para mí). Es bastante engorroso, pero no pude entender personalmente ningún otro método. Básicamente, combina la respuesta de Ryggyr aquí con otras respuestas en 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() 

La ventaja de este método es que, por varios diccionarios de fuentes que tiene, puede elegir diferentes fuentes/tamaños/pesos/colores para los distintos títulos, elegir el tipo de letra para las etiquetas señalizadoras, y elegir el tipo de letra para la leyenda, todo de forma independiente.


ACTUALIZACIÓN:

He elaborado un enfoque ligeramente diferente, menos desordenada que elimina los diccionarios de fuentes, y permite que cualquier fuente del sistema, incluso fuentes .otf. Para tener fuentes separadas para cada cosa, simplemente escriba más font_path y font_prop como variables.

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() 

Esperemos que esto es una respuesta integral

4

Sobre la base de las cosas más arriba:

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

Aquí es un totalmente enfoque diferente que funciona sorprendentemente bien para cambiar los tamaños de fuente:

¡Cambie figura tamaño!

que suelen utilizar código como este:

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) 

El más pequeño sea el tamaño de la figura, la mayor la fuente es correspondientes a la parcela. Esto también aumenta los marcadores. Tenga en cuenta que también configuro dpi o punto por pulgada. Aprendí esto al publicar el foro AMTA (American Modeling Teacher of America). Ejemplo: Figure from above code

+0

Wow. Eso funcionó bastante bien para mí. Gracias por compartir esta información. – muammar

68

Si usted es un monstruo de control como yo, puede que desee establecer explícitamente todos sus tamaños de fuente:

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 

Tenga en cuenta que también puede ajustar el tamaño de una llamada al método rc en matplotlib:

import matplotlib 

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

# and so on ... 
+2

Intenté muchas de las respuestas. Este se ve mejor, al menos en los cuadernos Jupyter. Simplemente copie el bloque de arriba en la parte superior y personalice las tres constantes de tamaño de fuente. – fviktor

+0

De acuerdo con fvitkor, ¡esa es la mejor respuesta! – SeF

2

estoy totalmente de acuerdo con el profesor Huster que la forma más sencilla de proceder es cambiar el tamaño de la figura, lo que permite mantener las fuentes predeterminadas. Solo tuve que complementar esto con una opción de bbox_inches al guardar la figura como un pdf porque las etiquetas de los ejes se cortaron.

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

Esta es una extensión a Marius Retegan answer. Puede crear un archivo JSON separado con todas sus modificaciones y luego cargarlo con rcParams.update. Estos cambios solo se aplicarán a la secuencia de comandos actual. Por lo tanto,

import json 
from matplotlib import pyplot as plt, rcParams 

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

y guarde este 'archivo_ejemplo.json' en la misma carpeta.

{ 
    "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": "" 
} 
Cuestiones relacionadas