07. Chart Recommendations

Chapter 7 of 18 · 20 min

Beyond single chart generation, AI can recommend visualization strategies for complete analyses. This involves understanding the analytical question, identifying relevant data aspects, and suggesting complementary views that build understanding progressively.

Effective visualization strategies combine summary views with detail views. A high-level overview shows patterns; subsequent views explore specific aspects. AI can plan this sequence by understanding typical analysis progressions.

Multi-View Analysis Planning

thorough analyses rarely rely on single charts. AI can recommend a sequence of views that build understanding systematically.

import ollama

def recommend_visualization_sequence(df: pd.DataFrame, question: str) -> list:
    """Recommend a sequence of visualizations to answer the question."""
    
    context = f"""Dataset with {len(df)} rows and {len(df.columns)} columns:
    {df.dtypes.to_dict()}
    
    Question: {question}
    
    Recommend an ordered sequence of visualizations (3-5 views) that:
    1. Start with overview/summary
    2. Progress to specific aspects
    3. Build toward answer
    
    For each view, specify: chart type, required columns, what to look for."""
    
    response = ollama.chat(
        model='llama3.2',
        messages=[{'role': 'user', 'content': context}]
    )
    
    return response['message']['content']

# Example planning
df = pd.DataFrame({
    'customer_id': range(1000),
    'age': [random.randint(18, 70) for _ in range(1000)],
    'income': [random.randint(30000, 150000) for _ in range(1000)],
    'churned': [random.choice([0, 1]) for _ in range(1000)]
})

sequence = recommend_visualization_sequence(
    df, 
    "What customer characteristics predict churn?"
)
print(sequence)

The response outlines a progression: start with churn rate overview, then examine distributions by churn status, then compare categorical factors, finally build predictive view.

Encoding Recommendations

Visual encoding choices significantly affect chart effectiveness. AI can recommend encodings appropriate for data types and analytical goals.

def recommend_encodings(df: pd.DataFrame, chart_type: str) -> dict:
    """Recommend encoding strategies for chart type."""
    
    prompt = f"""For a {chart_type}, recommend visual encodings for these columns:
    {df.dtypes.to_dict()}
    
    Consider: position, color, size, shape, angle.
    Recommend primary, secondary, and tertiary encoding assignments.
    Explain why each encoding choice fits the data."""
    
    response = ollama.chat(
        model='llama3.2',
        messages=[{'role': 'user', 'content': prompt}]
    )
    
    return response['message']['content']

Effective encoding follows perceptual principles. Position encodes quantitative values most accurately. Color hue works for categorical distinctions but not ordered values. Color saturation and size can encode magnitude. Shape works for categorical without inherent order.

Aesthetics and Accessibility

Charts should be visually clean and accessible to diverse audiences. AI recommendations can address these concerns.

def recommend_chart_aesthetics(chart_type: str, audience: str) -> dict:
    """Recommend aesthetic choices for chart type and audience."""
    
    prompt = f"""For a {chart_type} targeting {audience}, recommend:
    1. Color palette (consider colorblind accessibility)
    2. Font sizes for labels and titles
    3. Grid line usage
    4. Aspect ratio and dimensions
    5. Annotation usage
    6. Accessibility considerations"""
    
    response = ollama.chat(
        model='llama3.2',
        messages=[{'role': 'user', 'content': prompt}]
    )
    
    return response['message']['content']

Color palette selection requires considering color vision deficiencies. Avoiding red-green combinations, using patterns alongside colors, and testing with simulation tools improves accessibility.

EXERCISE

Develop a visualization recommendation function that accepts a question and dataset, outputs a sequence of 3-5 charts with specific parameters, and generates the corresponding code.