Генериране на диаграми и визуализации
На тази страница
Обновено на 2 ноември 2026 г. въз основа на документацията на OpenAI: инструментът Code Interpreter вече изисква параметър
container(добавен към всички примери), текстовите входни части използват типаinput_text, а уеб търсенето използва инструментаweb_search(web_search_previewвече е остарял инструмент без филтри за домейни). Генерираните файлове се извличат чрез функциитеfichiers_generesиtelechargerот Урок 10. Файловете, прикачени към съобщенията, се качват с целuser_data, което OpenAI препоръчва за входни данни на модела (File inputs). Източници: Code Interpreter · Web search.
Генериране на диаграми и визуализации
Диаграма, произведена от Code Interpreter, не е генерирано изображение: тя е резултат от изпълнението на реален скрипт на matplotlib върху вашите действителни данни. Тази разлика е важна – осите са точни, стойностите съвпадат с файла и можете да поискате кода, за да го възпроизведете локално.
В контейнера съществуват три библиотеки, всяка от които служи за различна цел. matplotlib обработва всичко, но може да бъде многословен. seaborn добавя статистически слой, който прави разпределенията и корелациите четими в един ред. plotly произвежда интерактивен HTML, най-подходящ за крайни продукти, които ще разглеждате с мишка. Посочете тази, която искате, във вашата подсказка; без инструкции моделът използва по подразбиране matplotlib.
Прости диаграми с 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")
Диаграми от данни във файл
Това е най-честият случай на употреба и там стойността е най-ясна: качвате файла, описвате диаграмата, която искате, и моделът се справя с четенето, типовете колони и самото чертане. Няма ръчни стъпки за подготовка и, което е още по-важно, няма ръчно преписване на числа – следователно няма грешки при копиране и поставяне.
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."
)
Статистически визуализации със seaborn
seaborn блести, когато въпросът засяга разпределение или връзка, а не поредица от стойности. Кутиева диаграма по категория или матрица на корелацията разкрива с един поглед онова, което таблица с числа показва едва след внимателно прочитане – и точно това трябва да прави една диаграма.
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."
)
Интерактивни диаграми с plotly
plotly променя естеството на крайния продукт: вместо статично изображение получавате самостоятелен HTML файл, в който можете да мащабирате, да задържате курсора за подробности и да филтрирате. Това е правилният избор за таблото за управление, което някой ще разглежда, но грешният избор за фигура, предназначена за печатен документ или имейл.
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")
Разширено персонализиране
Корпоративно ръководство за стил
Диаграма, генерирана по подразбиране, се разпознава веднага и изглежда аматьорска в корпоративен документ. Предаването на вашите цветове, шрифтове и конвенции в instructions е достатъчно, за да произвеждате последователни фигури от един отчет до следващия – и тъй като тези инструкции могат да се използват многократно, полагате усилието само веднъж.
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
)
Шаблон: генератор на визуални отчети
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)"
]
)
Съвети за качествени диаграми
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
"""
Ключови изводи
- matplotlib, seaborn и plotly са налични в пясъчника
- Предавайте данните си чрез
input_fileза диаграми, базирани на реални файлове - Дефинирайте ръководство за стил в
instructionsза постигане на последователност - Извличайте генерираните изображения от анотациите
container_file_citation, след което ги изтегляйте чрез API на контейнера (функцииfichiers_generesиtelechargerот Урок 10) - Plotly ви позволява да генерирате интерактивни HTML табла за управление