Generowanie wykresów i wizualizacji
Na tej stronie
Zaktualizowano 2 listopada 2026 na podstawie dokumentacji OpenAI: narzędzie Code Interpreter wymaga teraz parametru
container(dodano do wszystkich przykładów), części wejściowe tekstu używają typuinput_text, a wyszukiwanie w sieci korzysta z narzędziaweb_search(web_search_previewjest obecnie narzędziem przestarzałym bez filtrów domenowych). Wygenerowane pliki pobiera się za pomocą funkcjifichiers_generesitelechargerz Lekcji 10. Pliki dołączane do wiadomości są przesyłane z przeznaczeniemuser_data, co OpenAI rekomenduje dla danych wejściowych modelu (File inputs). Źródła: Code Interpreter · Web search.
Generowanie wykresów i wizualizacji
Wykres stworzony przez Code Interpreter nie jest wygenerowanym obrazem: to renderowanie rzeczywistego skryptu matplotlib wykonanego na Twoich prawdziwych danych. Ta różnica ma znaczenie – osie są precyzyjne, wartości zgadzają się z plikiem, a Ty możesz poprosić o kod, aby odtworzyć go lokalnie.
W kontenerze współistnieją trzy biblioteki, z których każda służy innemu celowi. matplotlib obsługuje wszystko, ale bywa rozwlekła. seaborn dodaje warstwę statystyczną, która sprawia, że rozkłady i korelacje stają się czytelne w jednej linii. plotly generuje interaktywny HTML, najlepiej zarezerwowany dla materiałów, które będziesz eksplorować za pomocą myszy. W poleceniu wskaż, której biblioteki chcesz użyć; bez instrukcji model domyślnie wybierze matplotlib.
Proste wykresy z 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")
Wykresy na podstawie danych z pliku
To najczęstszy przypadek użycia i sytuacja, w której wartość rozwiązania jest najbardziej oczywista: przesyłasz plik, opisujesz wykres, jakiego potrzebujesz, a model zajmuje się odczytem, typowaniem kolumn i rysowaniem. Żadnych ręcznych kroków przygotowawczych, a co kluczowe – żadnego ręcznego przepisywania liczb, więc zero błędów wynikających z kopiowania i wklejania.
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."
)
Wizualizacje statystyczne z seaborn
seaborn sprawdza się najlepiej, gdy pytanie dotyczy rozkładu lub zależności, a nie szeregu wartości. Wykres pudełkowy według kategorii lub macierz korelacji ujawniają natychmiast to, co tabela liczb pokazuje dopiero po uważnej lekturze – a dokładnie to powinien robić wykres.
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."
)
Wykresy interaktywne z plotly
plotly zmienia charakter deliverable: zamiast statycznego obrazu otrzymujesz samodzielny plik HTML, w którym możesz przybliżać, najechać kursorem i filtrować dane. To właściwy wybór dla dashboardu, który ktoś będzie eksplorować, ale zły wybór dla rysunku przeznaczonego do druku lub e-maila.
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")
Zaawansowane dostosowanie
Firmowy przewodnik stylów
Wykres wygenerowany domyślnie jest natychmiast rozpoznawalny i wygląda amatorsko w dokumentacji firmowej. Przekazanie swoich kolorów, czcionek i konwencji w polu instructions wystarczy, aby uzyskać spójne rysunki od jednego raportu do drugiego – a ponieważ te instrukcje można wielokrotnie wykorzystywać, wysiłek wkładasz tylko raz.
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
)
Wzorzec: generator raportów wizualnych
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)"
]
)
Wskazówki dotyczące jakości wykresów
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
"""
Kluczowe wnioski
- matplotlib, seaborn i plotly są dostępne w piaskownicy
- Przekaż swoje dane przez
input_file, aby tworzyć wykresy na podstawie rzeczywistych plików - Zdefiniuj przewodnik stylów w
instructions, aby zapewnić spójność - Pobierz wygenerowane obrazy z adnotacji
container_file_citation, a następnie ściągnij je przez API kontenera (funkcjefichiers_generesitelechargerz Lekcji 10) - Plotly pozwala generować interaktywne dashboardy w formacie HTML