Реализация AI-автоматической визуализации данных
AI-автовизуализация автоматически выбирает тип графика, оси, цвета и форматирование на основе типа данных и вопроса пользователя. Исключает ручной выбор между bar/line/scatter и устраняет типичные ошибки визуализации (pie charts с 20 сегментами, отсутствие подписей осей).
Автоматический выбор типа визуализации
from anthropic import Anthropic
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
class SmartVisualizer:
def __init__(self):
self.llm = Anthropic()
def visualize(self, df: pd.DataFrame, question: str = None) -> go.Figure:
"""Автоматический подбор визуализации"""
chart_config = self._determine_chart_config(df, question)
return self._render_chart(df, chart_config)
def _determine_chart_config(self, df: pd.DataFrame, question: str) -> dict:
schema = self._describe_dataframe(df)
response = self.llm.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=500,
messages=[{
"role": "user",
"content": f"""Given this dataframe and question, recommend the best visualization.
Data schema: {schema}
Question: {question or 'Show the data distribution'}
Return JSON with:
- chart_type: one of [bar, line, scatter, histogram, pie, heatmap, box, violin]
- x_column: column name for x axis
- y_column: column name for y axis (or list for multiple)
- color_column: column for color grouping (or null)
- title: chart title
- x_label: x axis label
- y_label: y axis label
- reasoning: brief explanation of choice"""
}]
)
return json.loads(response.content[0].text)
def _render_chart(self, df: pd.DataFrame, config: dict) -> go.Figure:
chart_type = config['chart_type']
chart_functions = {
'bar': lambda: px.bar(
df, x=config.get('x_column'), y=config.get('y_column'),
color=config.get('color_column'),
title=config.get('title', ''),
labels={config['x_column']: config.get('x_label', ''),
config['y_column']: config.get('y_label', '')}
),
'line': lambda: px.line(
df, x=config.get('x_column'), y=config.get('y_column'),
color=config.get('color_column'), title=config.get('title', '')
),
'scatter': lambda: px.scatter(
df, x=config.get('x_column'), y=config.get('y_column'),
color=config.get('color_column'), title=config.get('title', ''),
trendline='ols' if config.get('show_trendline') else None
),
'histogram': lambda: px.histogram(
df, x=config.get('x_column'), color=config.get('color_column'),
title=config.get('title', ''), nbins=30
),
'heatmap': lambda: px.imshow(
df.select_dtypes(include='number').corr(),
title=config.get('title', 'Correlation Matrix'),
text_auto=True, color_continuous_scale='RdBu_r'
),
'box': lambda: px.box(
df, x=config.get('x_column'), y=config.get('y_column'),
title=config.get('title', '')
),
}
render_fn = chart_functions.get(chart_type, chart_functions['bar'])
fig = render_fn()
# Стандартное оформление
fig.update_layout(
template='plotly_white',
font=dict(size=12),
title_font_size=16,
)
return fig
Мультиграфический дашборд
def create_auto_dashboard(df: pd.DataFrame) -> go.Figure:
"""Автоматический EDA дашборд"""
from plotly.subplots import make_subplots
num_cols = df.select_dtypes(include='number').columns.tolist()
cat_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()
n_plots = min(len(num_cols) + len(cat_cols[:3]), 9)
rows = (n_plots + 2) // 3
fig = make_subplots(rows=rows, cols=3, subplot_titles=[
*[f'Distribution: {c}' for c in num_cols[:6]],
*[f'Top values: {c}' for c in cat_cols[:3]]
])
idx = 1
for col in num_cols[:6]:
row, col_pos = (idx - 1) // 3 + 1, (idx - 1) % 3 + 1
fig.add_trace(
go.Histogram(x=df[col], name=col, nbinsx=30),
row=row, col=col_pos
)
idx += 1
for col in cat_cols[:3]:
row, col_pos = (idx - 1) // 3 + 1, (idx - 1) % 3 + 1
top_values = df[col].value_counts().head(10)
fig.add_trace(
go.Bar(x=top_values.index, y=top_values.values, name=col),
row=row, col=col_pos
)
idx += 1
fig.update_layout(height=300 * rows, showlegend=False, title="Data Overview")
return fig
Правильная автовизуализация сокращает время первичного EDA с 2-3 часов до 15-20 минут для стандартных датасетов.







