GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • PYTHON CHARTS
  • matplotlib
  • seaborn
  • plotly
  • pandas
  • colores
  • COLORES
  • PALETAS DE COLOR
  • R CODER
  • R CHARTS
  • Contacto
  • English

This view

  • Original page
  • New address

GeezerVison is showing python-charts.com — Fuentes en matplotlib

Busca un tutorial

INICIO MATPLOTLIB FUENTES

Fuentes en matplotlib

Matplotlib utiliza DejaVu Sans como fuente por defecto. Puedes cambiar la fuente y su tamaño para un solo elemento de texto o para todos los textos de tus gráficos a la vez.

Tamaño de fuente

Todas las funciones de texto (title, xlabel, ylabel, text, legend…) admiten el argumento fontsize (o size), ya sea un número en puntos o un tamaño relativo como "small", "large" o "x-large".

import matplotlib.pyplot as plt

genres = ["Fantasía", "Novela negra", "Romántica", "Ciencia ficción", "Historia"]
sales = [320, 280, 240, 190, 120]

fig, ax = plt.subplots()
ax.bar(genres, sales)

ax.set_title("Venta de libros", fontsize = 20)
ax.set_xlabel("Género", fontsize = 14)
ax.tick_params(labelsize = 8)
# plt.show()

Cambiar el tamaño de fuente de los textos en matplotlib

Cambiar todos los tamaños de fuente

Para cambiar el tamaño de todos los textos a la vez modifica font.size en rcParams. Los elementos concretos se pueden ajustar con claves como axes.titlesize, axes.labelsize, xtick.labelsize o legend.fontsize.

import matplotlib.pyplot as plt

plt.rcParams["font.size"] = 14
plt.rcParams["axes.titlesize"] = 18
plt.rcParams["xtick.labelsize"] = 10

Tipo de fuente

El argumento fontfamily (o family) admite el nombre de una fuente instalada en tu ordenador o una familia genérica: "serif", "sans-serif", "monospace", "cursive" o "fantasy".

import matplotlib.pyplot as plt

genres = ["Fantasía", "Novela negra", "Romántica", "Ciencia ficción", "Historia"]
sales = [320, 280, 240, 190, 120]

fig, ax = plt.subplots()
ax.barh(genres, sales, color = "#6D597A")

ax.set_title("Venta de libros", fontfamily = "serif", fontsize = 24)
ax.set_xlabel("Unidades vendidas", fontfamily = "monospace", fontsize = 13)
# plt.show()

Cambiar el tipo de fuente en matplotlib

Cambiar la fuente por defecto

Establece font.family en rcParams para usar la misma fuente en todos los gráficos. Puedes pasar una lista de fuentes por orden de preferencia.

import matplotlib.pyplot as plt

plt.rcParams["font.family"] = "serif"
plt.rcParams["font.serif"] = ["Times New Roman", "DejaVu Serif"]

Negrita y cursiva

Utiliza fontweight ("normal", "bold", "light" o un número entre 0 y 1000) y fontstyle ("normal", "italic" u "oblique").

import matplotlib.pyplot as plt

genres = ["Fantasía", "Novela negra", "Romántica", "Ciencia ficción", "Historia"]
sales = [320, 280, 240, 190, 120]

fig, ax = plt.subplots()
ax.bar(genres, sales)

ax.set_title("Título en negrita", fontweight = "bold")
ax.set_xlabel("Etiqueta en cursiva", fontstyle = "italic")
# plt.show()

Texto en negrita y cursiva en matplotlib

Varias propiedades a la vez

Guarda las propiedades de la fuente en un diccionario y pásalo con fontdict para reutilizarlas en varios elementos.

import matplotlib.pyplot as plt

font = {"family": "serif", "color": "darkred", "weight": "bold", "size": 16}

fig, ax = plt.subplots()
ax.set_title("Título", fontdict = font)
ax.set_xlabel("Eje X", fontdict = font)
# plt.show()

Listar las fuentes disponibles

El módulo font_manager lista las fuentes que matplotlib encuentra en tu sistema. Utiliza cualquiera de estos nombres en fontfamily.

from matplotlib import font_manager

fonts = sorted({f.name for f in font_manager.fontManager.ttflist})
print(fonts)

Usar una fuente personalizada

Para usar una fuente que no está instalada, como una fuente descargada de Google Fonts, agrega su archivo .ttf u .otf con addfont y después utiliza su nombre como cualquier otra fuente.

import matplotlib.pyplot as plt
from matplotlib import font_manager

font_manager.fontManager.addfont("Roboto-Regular.ttf")
plt.rcParams["font.family"] = "Roboto"

fig, ax = plt.subplots()
ax.set_title("Título con una fuente personalizada")
# plt.show()

Si matplotlib sigue usando la fuente por defecto, comprueba que el nombre que utilizas coincide con el que devuelve font_manager.FontProperties(fname = "Roboto-Regular.ttf").get_name(). Consulta también cómo personalizar los títulos y los textos.

R CODER website
Fundamentals of Data Visualization

Fundamentals of Data Visualization

A Primer on Making Informative and Compelling Figures

Comprar en Amazon
Better Data Visualizations

Better Data Visualizations

A Guide for Scholars, Researchers, and Wonks

Comprar en Amazon

También te puede interesar

Guardar gráficos en matplotlib

Guardar gráficos en matplotlib

Tipos de línea en matplotlib

Tipos de línea en matplotlib

Color de fondo en matplotlib

Color de fondo en matplotlib

Personalización de los ejes en matplotlib

Personalización de los ejes en matplotlib

Barra de color en matplotlib

Barra de color en matplotlib

Agregar un grid en matplotlib

Agregar un grid en matplotlib

Tamaño de la figura en matplotlib

Tamaño de la figura en matplotlib

Textos y anotaciones en matplotlib

Textos y anotaciones en matplotlib

Títulos en matplotlib

Títulos en matplotlib

Leyenda en matplotlib

Leyenda en matplotlib

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.