Generar gráficos y visualizaciones
En esta página
Actualizado el 2 de noviembre de 2026 según la documentación de OpenAI: la herramienta Code Interpreter requiere ahora un parámetro
container(añadido a todos los ejemplos), las partes de entrada de texto utilizan el tipoinput_texty la búsqueda web emplea la herramientaweb_search(web_search_previewes ahora una herramienta heredada sin filtros de dominio). Los archivos generados se recuperan mediante las funcionesfichiers_generesytelechargerde la Lección 10. Los archivos adjuntos a los mensajes se suben con el propósitouser_data, que OpenAI recomienda para las entradas del modelo (Entradas de archivo). Fuentes: Code Interpreter · Búsqueda web.
Generar gráficos y visualizaciones
Un gráfico producido por Code Interpreter no es una imagen generada: es la representación de un script real de matplotlib ejecutado sobre tus datos reales. Esta distinción es importante: los ejes son precisos, los valores coinciden con el archivo y puedes solicitar el código para reproducirlo localmente.
Tres bibliotecas coexisten en el contenedor, cada una con un propósito diferente. matplotlib lo gestiona todo, pero puede ser verbosa. seaborn añade una capa estadística que hace legibles las distribuciones y correlaciones en una sola línea. plotly produce HTML interactivo, ideal para entregables que explorarás con el ratón. Nombra la que quieras en tu prompt; sin instrucciones, el modelo utiliza matplotlib por defecto.
Gráficos sencillos con matplotlib
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.6-terra",
input="Create a bar chart showing monthly sales: "
"Jan=120, Feb=98, Mar=145, Apr=167, May=189, Jun=210, "
"Jul=195, Aug=178, Sep=220, Oct=245, Nov=267, Dec=312. "
"Professional style, blue colors, title and labels.",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
instructions="Use matplotlib with a professional style. "
"Sans-serif font, light grid, no top or right spines."
)
# Retrieve the generated image
for ann in fichiers_generes(response):
telecharger(client, ann, "monthly_sales.png")
Gráficos a partir de datos de archivos
Este es el caso de uso más frecuente y donde el valor resulta más evidente: subes el archivo, describes el gráfico que deseas y el modelo se encarga de la lectura, la tipificación de columnas y el trazado. No hay pasos de preparación manual y, lo que es más importante, no hay transcripción manual de números, por lo que se evitan errores de copiar y pegar.
with open("team_performance.csv", "rb") as f:
file_obj = client.files.create(file=f, purpose="user_data")
response = client.responses.create(
model="gpt-5.6-terra",
input=[{
"role": "user",
"content": [
{"type": "input_text", "text": (
"From this file, create a dashboard with 4 charts: "
"1. Monthly revenue evolution (line chart) "
"2. Breakdown by product category (pie chart) "
"3. Top 10 clients by revenue (horizontal bar chart) "
"4. Correlation between quantity and amount (scatter plot) "
"Arrange the 4 charts in a 2x2 grid."
)},
{"type": "input_file", "file_id": file_obj.id}
]
}],
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
instructions="Create a matplotlib figure with 4 subplots. "
"Use a consistent color palette. "
"Resolution 1920x1080, DPI 150. "
"Export as high-quality PNG."
)
Visualizaciones estadísticas con seaborn
seaborn destaca cuando la pregunta concerne a una distribución o a una relación en lugar de a una serie de valores. Un diagrama de cajas por categoría o una matriz de correlación revela de un vistazo lo que una tabla de números solo muestra tras una lectura cuidadosa, y eso es exactamente lo que debe hacer un gráfico.
response = client.responses.create(
model="gpt-5.6-terra",
input=[{
"role": "user",
"content": [
{"type": "input_text", "text": (
"Visual statistical analysis of this data: "
"1. Heatmap of the correlation matrix "
"2. Distribution of each numerical variable (histograms + KDE) "
"3. Boxplots by category to identify outliers "
"4. Pairplot of the 5 main variables"
)},
{"type": "input_file", "file_id": file_obj.id}
]
}],
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
instructions="Use seaborn with the 'whitegrid' theme. "
"Annotate values in the heatmap. "
"Use the 'coolwarm' palette for correlations."
)
Gráficos interactivos con plotly
plotly cambia la naturaleza del entregable: en lugar de una imagen estática, obtienes un archivo HTML independiente donde puedes hacer zoom, pasar el cursor y filtrar. Es la elección correcta para un panel que alguien va a explorar, pero la incorrecta para una figura destinada a un documento impreso o un correo electrónico.
response = client.responses.create(
model="gpt-5.6-terra",
input=[{
"role": "user",
"content": [
{"type": "input_text", "text": (
"Create an interactive plotly chart showing sales evolution with: "
"- Zoom and date range selection "
"- Hover tooltips with details "
"- Buttons to filter by category "
"- Export as standalone HTML file"
)},
{"type": "input_file", "file_id": file_obj.id}
]
}],
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}]
)
# Retrieve the interactive HTML file
for ann in fichiers_generes(response):
if ann.filename.endswith(".html"):
telecharger(client, ann, "interactive_dashboard.html")
Personalización avanzada
Guía de estilo corporativa
Un gráfico generado por defecto es inmediatamente reconocible y parece amateur en un documento corporativo. Pasar tus colores, fuentes y convenciones en instructions es suficiente para producir figuras coherentes de un informe a otro y, dado que estas instrucciones son reutilizables, solo haces el esfuerzo una vez.
STYLE_GUIDE = """
Visualization rules:
- Primary color: #1E3A5F (navy blue)
- Secondary color: #E74C3C (red)
- Accent color: #F39C12 (orange)
- Background: white (#FFFFFF)
- Font: sans-serif
- No borders around charts
- Light gray grid (#E0E0E0)
- Bold title, size 14
- Axis labels size 11
- Legend at bottom right
- Always include data source at bottom left
- Minimum resolution: 1200x800 pixels
"""
response = client.responses.create(
model="gpt-5.6-terra",
input=[{
"role": "user",
"content": [
{"type": "input_text", "text": "Create a quarterly revenue evolution chart"},
{"type": "input_file", "file_id": file_obj.id}
]
}],
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
instructions=STYLE_GUIDE
)
Patrón: generador de informes visuales
def generate_visual_report(
file_path: str,
report_title: str,
sections: list[str]
) -> list[str]:
"""Generate a report with charts from data."""
with open(file_path, "rb") as f:
file_obj = client.files.create(file=f, purpose="user_data")
images = []
for i, section in enumerate(sections):
response = client.responses.create(
model="gpt-5.6-terra",
input=[{
"role": "user",
"content": [
{"type": "input_text", "text": f"Section {i+1} of report '{report_title}': {section}"},
{"type": "input_file", "file_id": file_obj.id}
]
}],
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
instructions=(
"Create a professional chart for this section. "
"Include a descriptive title and relevant annotations. "
"Export as PNG 1200x800 DPI 150."
)
)
for ann in fichiers_generes(response):
name = f"report_section_{i+1}.png"
telecharger(client, ann, name)
images.append(name)
return images
# Usage
charts = generate_visual_report(
"annual_sales.csv",
"2025 Sales Report",
[
"Monthly revenue evolution with trend",
"Sales breakdown by region (map or treemap)",
"Performance comparison by sales rep (grouped bars)",
"Forecasts for the next 3 months (with confidence interval)"
]
)
Consejos para gráficos de calidad
quality_instructions = """
For each chart:
- Choose the chart type best suited to the data
- Use accessible colors (sufficient contrast)
- Avoid 3D charts unless explicitly requested
- Limit pie charts to 6 categories maximum
- Add annotations for important points
- Use appropriate scales (no truncated zero unless justified)
- Always export in high resolution
"""
Puntos clave
- matplotlib, seaborn y plotly están disponibles en el entorno aislado
- Pasa tus datos mediante
input_filepara gráficos basados en archivos reales - Define una guía de estilo en
instructionspara garantizar la coherencia - Recupera las imágenes generadas a partir de las anotaciones
container_file_citationy descárgalas luego mediante la API del contenedor (funcionesfichiers_generesytelechargerde la Lección 10) - Plotly te permite generar paneles interactivos en HTML