Gerar gráficos e visualizações
Nesta página
Atualizado em 2 de novembro de 2026 com base na documentação da OpenAI: a ferramenta Code Interpreter requer agora um parâmetro
container(adicionado a todos os exemplos), as partes de entrada de texto utilizam o tipoinput_texte a pesquisa na web utiliza a ferramentaweb_search(web_search_previewé agora uma ferramenta legada sem filtros de domínio). Os ficheiros gerados são recuperados através das funçõesfichiers_generesetelechargerda Lição 10. Os ficheiros anexados às mensagens são carregados com o propósitouser_data, que a OpenAI recomenda para entradas do modelo (File inputs). Fontes: Code Interpreter · Web search.
Gerar gráficos e visualizações
Um gráfico produzido pelo Code Interpreter não é uma imagem gerada: é o resultado da execução de um script matplotlib real sobre os seus dados verdadeiros. Esta distinção é importante — os eixos são precisos, os valores correspondem ao ficheiro e pode solicitar o código para o reproduzir localmente.
Três bibliotecas coexistem no contentor, cada uma servindo um propósito diferente. O matplotlib trata de tudo, mas pode ser verboso. O seaborn adiciona uma camada estatística que torna as distribuições e correlações legíveis numa única linha. O plotly produz HTML interativo, ideal para entregáveis que irá explorar com o rato. Indique qual deseja no seu prompt; sem instruções, o modelo assume o matplotlib por padrão.
Gráficos simples com 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 dados de ficheiros
Este é o caso de uso mais comum e onde o valor é mais evidente: carrega o ficheiro, descreve o gráfico que deseja e o modelo trata da leitura, da tipagem das colunas e da criação do gráfico. Sem etapas de preparação manual e, crucialmente, sem transcrição manual de números — logo, sem erros de copiar e colar.
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."
)
Visualizações estatísticas com seaborn
O seaborn destaca-se quando a questão concerne uma distribuição ou uma relação, em vez de uma série de valores. Um diagrama de caixa por categoria ou uma matriz de correlação revela num instante o que uma tabela de números só mostra após uma leitura atenta — e é exatamente isso que um gráfico deve fazer.
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 interativos com plotly
O plotly altera a natureza do entregável: em vez de uma imagem estática, obtém um ficheiro HTML autónomo onde pode fazer zoom, passar o rato e filtrar. É a escolha certa para um painel que alguém irá explorar, mas a escolha errada para uma figura destinada a um documento impresso ou e-mail.
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")
Personalização avançada
Guia de estilo corporativo
Um gráfico gerado por padrão é imediatamente reconhecível e parece amador num documento corporativo. Passar as suas cores, tipos de letra e convenções em instructions é suficiente para produzir figuras consistentes de um relatório para o outro — e como estas instruções são reutilizáveis, só precisa de fazer o esforço uma 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
)
Padrão: gerador de relatórios visuais
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)"
]
)
Dicas para gráficos de qualidade
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
"""
Pontos-chave
- matplotlib, seaborn e plotly estão disponíveis na sandbox
- Passe os seus dados via
input_filepara gráficos baseados em ficheiros reais - Defina um guia de estilo em
instructionspara garantir consistência - Recupere as imagens geradas das anotações
container_file_citatione transfira-as através da API do contentor (funçõesfichiers_generesetelechargerda Lição 10) - O plotly permite gerar painéis HTML interativos