Skip to main content
Editor

Data Visualization: Choose the Right Chart and Tell a Story

Advanced25 min5 exercises100 XP
0/5 exercises

A chart that looks pretty but tells the wrong story is worse than no chart at all. In 1986, NASA engineers showed managers a chart arguing that cold temperatures could damage the Space Shuttle Challenger's O-ring seals. The chart was so poorly designed that the managers couldn't see the pattern. The shuttle launched the next day and broke apart 73 seconds after liftoff.

Good data visualization isn't just about making things look nice. It's about choosing the right chart type, avoiding misleading scales, making data accessible to everyone, and ultimately telling a clear story. This tutorial teaches you the principles that separate effective visualizations from confusing ones.

Which Chart Type Should You Use?

The most common mistake in data visualization is picking the wrong chart type. A pie chart for 20 categories? Unreadable. A line chart for categorical data? Misleading. The right chart depends on what question you're answering.

Here's a decision framework:

  • Comparing categories? Use a bar chart.
  • Showing change over time? Use a line chart.
  • Showing relationships between two variables? Use a scatter plot.
  • Showing parts of a whole? Use a pie chart (only with 2-5 categories) or a stacked bar.
  • Showing distribution? Use a histogram or box plot.
  • Chart type decision helper
    # Decision helper: what chart type fits your data?
    def suggest_chart(question_type, num_categories=None):
    '''Suggest the best chart type based on what you want to show.'''
    charts = {
    'comparison': 'Bar chart',
    'trend': 'Line chart',
    'relationship': 'Scatter plot',
    'distribution': 'Histogram',
    'composition': 'Stacked bar chart' if (num_categories or 0) > 5 else 'Pie chart',
    'ranking': 'Horizontal bar chart',
    }
    return charts.get(question_type, 'Unknown type')
    # Test the helper
    print(suggest_chart('comparison'))
    print(suggest_chart('trend'))
    print(suggest_chart('relationship'))
    print(suggest_chart('composition', num_categories=3))
    print(suggest_chart('composition', num_categories=10))
    print(suggest_chart('ranking'))
    Output
    Bar chart
    Line chart
    Scatter plot
    Pie chart
    Stacked bar chart
    Horizontal bar chart

    What Makes a Chart Misleading?

    A chart can be technically accurate but visually deceptive. News outlets, advertisers, and even well-meaning analysts create misleading charts all the time. Learning to spot these tricks makes you a better data consumer and a more honest data presenter.

    The Truncated Y-Axis Trick

    The most common trick is starting the y-axis at a number other than zero. This magnifies small differences and makes them look enormous. A 2% change can look like a 200% change.

    The truncated y-axis deception
    # Demonstrating how truncated axes mislead
    quarters = ['Q1', 'Q2', 'Q3', 'Q4']
    revenue = [98, 100, 102, 104] # Small 2% growth each quarter
    # Calculate what the viewer perceives
    full_range = max(revenue) - 0 # Honest: from 0
    truncated_range = max(revenue) - 95 # Misleading: from 95
    actual_growth = (revenue[-1] - revenue[0]) / revenue[0] * 100
    print('Actual revenue growth: {:.1f}%'.format(actual_growth))
    print()
    print('With y-axis starting at 0:')
    print(' Visual bar ratio (Q4/Q1): {:.2f}x'.format(revenue[-1] / revenue[0]))
    print(' Looks like: modest, steady growth')
    print()
    print('With y-axis starting at 95:')
    print(' Visual bar ratio (Q4/Q1): {:.2f}x'.format(
    (revenue[-1] - 95) / (revenue[0] - 95)
    ))
    print(' Looks like: explosive tripling of revenue!')
    print()
    print('Same data, completely different stories.')
    Output
    Actual revenue growth: 6.1%
    
    With y-axis starting at 0:
      Visual bar ratio (Q4/Q1): 1.06x
      Looks like: modest, steady growth
    
    With y-axis starting at 95:
      Visual bar ratio (Q4/Q1): 3.00x
      Looks like: explosive tripling of revenue!
    
    Same data, completely different stories.

    Cherry-Picking Time Ranges

    Another deceptive technique is choosing a time range that supports your narrative while hiding the bigger picture. A stock that's up 5% this month might be down 40% this year.

    Cherry-picking time ranges
    # Same dataset, different stories
    monthly_users = {
    'Jan': 1000, 'Feb': 950, 'Mar': 900, 'Apr': 880,
    'May': 870, 'Jun': 860, 'Jul': 850, 'Aug': 855,
    'Sep': 870, 'Oct': 890, 'Nov': 910, 'Dec': 930
    }
    all_months = list(monthly_users.keys())
    all_values = list(monthly_users.values())
    # Story 1: "We're growing!" (Aug-Dec only)
    late_months = all_months[7:]
    late_values = all_values[7:]
    growth = (late_values[-1] - late_values[0]) / late_values[0] * 100
    print('Story 1 (Aug-Dec): "Users grew {:.1f}%!"'.format(growth))
    # Story 2: "We're shrinking!" (Full year)
    full_change = (all_values[-1] - all_values[0]) / all_values[0] * 100
    print('Story 2 (Full year): "Users dropped {:.1f}%"'.format(full_change))
    print()
    print('Both are technically true. Only one gives the full picture.')
    Output
    Story 1 (Aug-Dec): "Users grew 8.8%!"
    Story 2 (Full year): "Users dropped -7.0%"
    
    Both are technically true. Only one gives the full picture.

    How Do You Make Charts Accessible to Everyone?

    About 8% of men and 0.5% of women have some form of color vision deficiency. If your chart relies solely on color to distinguish data series, these readers can't understand it. Accessibility isn't just nice to have - in many organizations, it's a legal requirement.

    Here are the key principles for accessible visualizations:

  • Don't rely on color alone. Use different line styles (solid, dashed, dotted) and markers (circles, squares, triangles) alongside colors.
  • Use colorblind-safe palettes. Avoid red-green combinations. Blue-orange is usually safe.
  • Add direct labels instead of relying on legends that require color matching.
  • Use sufficient contrast between data and background.
  • Accessible color palette
    # Building an accessible color palette
    def create_accessible_palette():
    '''Returns a colorblind-friendly palette with descriptions.'''
    palette = {
    'blue': '#0072B2',
    'orange': '#E69F00',
    'green': '#009E73',
    'vermillion': '#D55E00',
    'sky_blue': '#56B4E9',
    'yellow': '#F0E442',
    'purple': '#CC79A7',
    'black': '#000000',
    }
    return palette
    palette = create_accessible_palette()
    print('Colorblind-friendly palette (Wong, 2011):')
    for name, hex_code in palette.items():
    print(f' {name:12s} -> {hex_code}')
    print('\nTip: Pair these colors with different markers and line styles')
    print('for maximum accessibility.')
    Output
    Colorblind-friendly palette (Wong, 2011):
      blue         -> #0072B2
      orange       -> #E69F00
      green        -> #009E73
      vermillion   -> #D55E00
      sky_blue     -> #56B4E9
      yellow       -> #F0E442
      purple       -> #CC79A7
      black        -> #000000
    
    Tip: Pair these colors with different markers and line styles
    for maximum accessibility.

    How Do You Tell a Story with Data?

    The difference between a chart and a data story is context. A chart shows numbers. A story explains what those numbers mean, why they matter, and what should happen next.

    Every good data story has three parts:

  • Setup - what's the context? ("We launched a new feature in March.")
  • Conflict - what's the interesting finding? ("Engagement dropped 15% in the first week.")
  • Resolution - what does it mean? ("Users needed a tutorial. After we added one, engagement rose 40%.")
  • Building a data narrative
    # Data storytelling: annotations transform charts into narratives
    def build_story_annotations(data, events):
    '''Match data points with contextual events to build a narrative.'''
    story_points = []
    for month, event in events.items():
    if month in data:
    story_points.append({
    'month': month,
    'value': data[month],
    'event': event,
    })
    return story_points
    monthly_signups = {
    'Jan': 500, 'Feb': 520, 'Mar': 480, 'Apr': 390,
    'May': 350, 'Jun': 410, 'Jul': 550, 'Aug': 680,
    'Sep': 720, 'Oct': 750, 'Nov': 800, 'Dec': 830
    }
    key_events = {
    'Apr': 'Competitor launched rival product',
    'Jun': 'New marketing campaign started',
    'Aug': 'Product redesign released',
    }
    story = build_story_annotations(monthly_signups, key_events)
    print('Key Story Points:')
    for point in story:
    print(f' {point["month"]}: {point["value"]} signups - {point["event"]}')
    print(f'\nNarrative: Signups dipped in Apr due to competition,')
    print(f'recovered with marketing in Jun, and surged after redesign in Aug.')
    Output
    Key Story Points:
      Apr: 390 signups - Competitor launched rival product
      Jun: 410 signups - New marketing campaign started
      Aug: 680 signups - Product redesign released
    
    Narrative: Signups dipped in Apr due to competition,
    recovered with marketing in Jun, and surged after redesign in Aug.

    What Are the Most Common Visualization Mistakes?

    Even experienced data scientists make these mistakes. Here's a checklist of things to watch for before sharing any visualization.

    Visualization quality checker
    # Visualization quality checklist
    def check_visualization(config):
    '''Run a quality check on visualization configuration.'''
    issues = []
    if not config.get('title'):
    issues.append('Missing title - every chart needs one')
    if not config.get('axis_labels'):
    issues.append('Missing axis labels - readers can\'t interpret unlabeled axes')
    if config.get('chart_type') == 'pie' and config.get('categories', 0) > 5:
    issues.append(f'Pie chart with {config["categories"]} categories - use a bar chart instead')
    if config.get('y_starts_at') and config.get('y_starts_at') != 0 and config.get('chart_type') == 'bar':
    issues.append('Bar chart with non-zero baseline - this distorts proportions')
    if config.get('uses_3d'):
    issues.append('3D chart - 3D adds no information and distorts perspective')
    if not config.get('color_accessible'):
    issues.append('Colors may not be accessible - test with colorblind simulator')
    if config.get('dual_axes') and not config.get('dual_axes_justified'):
    issues.append('Dual axes without justification - consider separate charts')
    return issues
    # Check a problematic chart
    bad_chart = {
    'title': '',
    'axis_labels': False,
    'chart_type': 'pie',
    'categories': 12,
    'uses_3d': True,
    'color_accessible': False,
    }
    issues = check_visualization(bad_chart)
    print(f'Found {len(issues)} issues:')
    for i, issue in enumerate(issues, 1):
    print(f' {i}. {issue}')
    print()
    # Check a good chart
    good_chart = {
    'title': 'Monthly Revenue by Region',
    'axis_labels': True,
    'chart_type': 'bar',
    'categories': 4,
    'y_starts_at': 0,
    'uses_3d': False,
    'color_accessible': True,
    }
    issues = check_visualization(good_chart)
    print(f'Found {len(issues)} issues:', 'None! Great chart.' if not issues else '')
    for issue in issues:
    print(f' - {issue}')
    Output
    Found 5 issues:
      1. Missing title - every chart needs one
      2. Missing axis labels - readers can't interpret unlabeled axes
      3. Pie chart with 12 categories - use a bar chart instead
      4. 3D chart - 3D adds no information and distorts perspective
      5. Colors may not be accessible - test with colorblind simulator
    
    Found 0 issues: None! Great chart.

    Practice Exercises

    Choose the Right Chart Type
    Write Code

    Write a function choose_chart(data_description) that takes a string describing the data and returns the best chart type. Handle these cases: if the description contains "over time" or "trend", return 'line'. If it contains "compare" or "categories", return 'bar'. If it contains "relationship" or "correlation", return 'scatter'. If it contains "distribution", return 'histogram'. If it contains "proportion" or "percentage", return 'bar' (not pie -- bar is almost always better). Otherwise return 'bar' as the safe default. Test with the provided descriptions.

    def choose_chart(data_description):
    desc = data_description.lower()
    # Your logic here
    pass
    # Test cases
    print(choose_chart('Sales over time for 2024'))
    print(choose_chart('Compare revenue across departments'))
    print(choose_chart('Relationship between age and income'))
    print(choose_chart('Distribution of test scores'))
    print(choose_chart('Proportion of budget by category'))
    Detect Misleading Chart Configurations
    Write Code

    Write a function find_issues(config) that takes a dictionary with chart configuration and returns a list of issue strings. Check for these problems: (1) If y_min is not 0 and chart_type is 'bar', add 'truncated axis'. (2) If categories > 6 and chart_type is 'pie', add 'too many pie slices'. (3) If is_3d is True, add 'unnecessary 3d'. (4) If has_title is False, add 'missing title'. Print the sorted issues for the test config.

    def find_issues(config):
    issues = []
    # Check for problems
    return sorted(issues)
    # Test with a problematic chart
    test_config = {
    'chart_type': 'pie',
    'categories': 10,
    'y_min': 50,
    'is_3d': True,
    'has_title': False,
    }
    result = find_issues(test_config)
    for issue in result:
    print(issue)
    Build Accessible Chart Configurations
    Write Code

    Write a function make_accessible(series_count) that returns a list of dictionaries, each with keys 'color', 'marker', and 'linestyle' for making chart lines distinguishable without relying on color alone. Use these colors in order: '#0072B2', '#E69F00', '#009E73', '#D55E00'. Use these markers: 'o', 's', '^', 'D'. Use these linestyles: '-', '--', '-.', ':'. Return configs for the first series_count series. Print each config for series_count=3.

    def make_accessible(series_count):
    colors = ['#0072B2', '#E69F00', '#009E73', '#D55E00']
    markers = ['o', 's', '^', 'D']
    linestyles = ['-', '--', '-.', ':']
    # Build and return configs
    pass
    configs = make_accessible(3)
    for c in configs:
    print(c)
    Calculate the Deception Factor
    Predict Output

    What will this code print? It calculates how much a truncated y-axis exaggerates the visual difference between two bars.

    bar_a = 95
    bar_b = 100
    # Honest chart (y starts at 0)
    honest_ratio = bar_b / bar_a
    # Truncated chart (y starts at 90)
    truncated_ratio = (bar_b - 90) / (bar_a - 90)
    print(round(honest_ratio, 2))
    print(round(truncated_ratio, 2))
    Build a Data Story with Key Events
    Write Code

    Write a function build_narrative(data, events) where data is a dict of {month: value} and events is a dict of {month: event_description}. The function should return a list of strings, one per event, in the format 'MONTH: VALUE - EVENT'. Only include months that appear in both dicts. Print each narrative line for the test data.

    def build_narrative(data, events):
    # Build narrative lines for months that have both data and events
    pass
    data = {
    'Jan': 1000, 'Feb': 1100, 'Mar': 900,
    'Apr': 950, 'May': 1200, 'Jun': 1400
    }
    events = {
    'Mar': 'Server outage',
    'May': 'Marketing campaign launched',
    'Jun': 'Product featured on news',
    }
    narrative = build_narrative(data, events)
    for line in narrative:
    print(line)

    Harder problems

    More problems on this topic: Working with data

    Related Tutorials

    Was this tutorial helpful?