Featured resource
Tech Upskilling Playbook 2025
Tech Upskilling Playbook

Build future-ready tech teams and hit key business milestones with seven proven plays from industry leaders.

Learn more
  • Labs icon Lab
  • Data
Labs

Build a Bar Chart in Python to Visualize Hospital Performance Metrics

In this Code Lab, you'll visualize hospital satisfaction data using Matplotlib and Seaborn. Starting with basic bar charts, you’ll apply essential techniques such as labeling axes, customizing colors, and adjusting layout styles. You’ll also practice adding titles, rotating tick labels, styling with transparency and outlines, and experimenting with grouped and stacked charts. By the end, you’ll know how to annotate and export polished visualizations that highlight key healthcare performance metrics.

Labs

Path Info

Level
Clock icon Intermediate
Duration
Clock icon 1h 37m
Last updated
Clock icon Aug 26, 2025

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Table of Contents

  1. Challenge

    Step 1: Create Your First Bar Chart

    Step 1: Create Your First Bar Chart

    Hospital systems often rely on satisfaction surveys to assess how patients feel about the care they received. These scores can influence funding, reputation, and improvement strategies.

    In this Code Lab, you'll start by creating simple bar charts to visualize satisfaction scores from multiple hospitals. You’ll learn how to use both:

    • Matplotlib’s plt.bar() function (imperative style)
    • Seaborn's sns.barplot() function (declarative style)

    Both tool helps you visualize data, but they differ in how much you control versus how much is automated.

    What You’ll Learn in This Step

    • Build a basic vertical bar chart using Matplotlib
    • Recreate it using Seaborn’s barplot() function
    • Understand how both libraries render bar charts differently

    You'll complete all tasks in a Jupyter notebook rather than in standalone .py files.

    Open the Notebook

    • Navigate to the workspace in the right panel.
    • Open the file: step-one.ipynb.
    Important: You must run the cell before clicking Validate.
    How to Complete Each Task > * Find the matching **code cell** labeled **Task 1.1**, **Task 1.2**, etc. > * Write your code directly in that cell. > * Run the cell using the **Run** button or by pressing `Shift+Enter`. > * Save your progress using the **Save icon** or **File > Save and Checkpoint**. > * You do not need to use the terminal, create additional files, or call `plt.savefig()`. All code and output will appear inline.
    ### `medicalPatients.csv` Dataset Overview

    For this lab, you’ll use the dataset located at data/medicalPatients.csv. It contains demographic and diagnostic information for hospital patients.

    Dataset Overview

    | Column Name | Description | | ---------------- | ------------------------------------------- | | patient_id | Unique patient identifier | | patient_name | Full name of the patient | | gender | Categorical (Male, Female) | | date_of_birth | Patient’s date of birth | | visit_date | Date of hospital visit | | symptoms | Reported symptoms during the visit | | diagnosis | Medical condition diagnosed | | medication | Name of the prescribed medication | | dosage | Medication dosage (e.g., "500mg") |

    ### Using `plt.bar()` to Create Bar Charts in Python

    To visualize categorical data using Matplotlib, use the plt.bar() function to generate vertical bar graphs.

    Syntax Breakdown: plt.bar(x, height)
    import matplotlib.pyplot as plt
    
    plt.bar(x=['A', 'B', 'C'], height=[10, 20, 15])
    plt.show()
    
    • x: A list or array of category labels (for example, "Diagnosis A", "Diagnosis B").
    • height: A list or array of numerical values associated with each label (e.g., number of patients)
    • plt.show(): Displays the plot inline when run in a Jupyter notebook
    ### Using `sns.barplot()` for Declarative Charting

    While matplotlib.pyplot gives you full control over how charts are constructed, it can be more manual. For cleaner, faster visualizations, many analysts use Seaborn—a library that automates chart layout and statistical aggregation.

    The sns.barplot() function builds bar charts directly from a DataFrame. You specify which columns should represent the x-axis (categories) and y-axis (values), and it does the rest.

    Syntax Breakdown: sns.barplot(x=..., y=..., data=...)
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.barplot(x="category_column", y="numeric_column", data=table_name, estimator=function)
    plt.show()
    
    • x: Name of the categorical column (e.g., types or groups)
    • y: Name of the numeric column you want to summarize
    • data: The DataFrame you’re plotting from
    • estimator: Optional — tells Seaborn how to aggregate values (e.g., len, mean, sum)

    You’ll use this approach to recreate the same diagnosis chart—showing how Seaborn can handle counting and plotting in fewer lines of code.

  2. Challenge

    Step 2: Add Labels and Title

    Step 2: Add Labels and Titles

    Charts without titles, axis labels, or tick formatting can confuse or mislead your audience—even when the data itself is accurate. This step helps you transform basic bar charts into clear, presentation-ready visuals by:

    • Adding axis labels to clarify units and categories
    • Applying chart titles to summarize the message
    • Rotating long tick labels for better legibility

    These finishing touches ensure your visualizations are interpretable and professional—both essentials for any reporting or stakeholder deliverables.

    What You’ll Learn in This Step

    • Use plt.xlabel() and plt.ylabel() to define axis labels
    • Use plt.title() to summarize your chart’s purpose
    • Rotate tick labels using plt.xticks(rotation=...) for clarity

    You'll complete all tasks in a Jupyter notebook rather than in standalone .py files.

    Open the Notebook

    • Open the file: step-two.ipynb in the workspace.
    Important: You must run the cell before clicking Validate.
    How to Complete Each Task > * Find the matching **code cell** labeled **Task 2.1**, **Task 2.2**, etc. > * Write your code directly in that cell. > * Run the cell using the **Run** button or `Shift+Enter`. > * Save your progress using the **Save** icon or **File > Save and Checkpoint**. > * You do not need to use the terminal or create extra files—all code and output will appear directly in the notebook.
    --- ### Add Labels and a Title with Matplotlib

    When building data visualizations, chart readability is just as important as the data itself. That’s where axis labels, titles, and tick formatting come in.

    Matplotlib gives you a few essential tools for this:

    Syntax Overview
    plt.xlabel("X-axis label")
    plt.ylabel("Y-axis label")
    plt.title("Chart Title")
    plt.xticks(rotation=45)
    
    • xlabel() and ylabel() describe what each axis is measuring
    • title() explains what the chart is about overall
    • xticks(rotation=...) helps fix overlapping labels (such as long category names)

    You’ll now take the basic bar chart you created earlier and refine it for clarity and presentation. Across the next few tasks, you’ll focus on key improvements like adding labels, applying a title, and adjusting tick readability. ---

    Add a Title Using plt.title()

    A chart title is often the first thing a viewer sees—it helps them understand what the data represents without needing to decode axis labels or dive into the chart structure.

    Matplotlib allows you add a title using a simple, single function:

    Syntax Overview
    plt.title("Descriptive Chart Title")
    

    The title should summarize the chart’s key insight clearly and succinctly. It typically appears at the top and is added after you've built your plot.


    Adjust Tick Labels for Readability

    Tick labels help your audience understand what each bar or point in a chart represents. But when labels are long—like diagnosis names—they can overlap or become unreadable.

    Matplotlib and Seaborn both provide ways to fix this.

    Matplotlib Tick Rotation
    plt.xticks(rotation=45)
    
    • Rotates the labels on the x-axis by 45 degrees.
    • You can adjust the angle (e.g., 30, 60, 90) for layout clarity.
    Seaborn Context and Styling
    import seaborn as sns
    sns.set(style="whitegrid", context="talk")
    
    • style controls the background grid and chart aesthetics.
    • context adjusts the scale of fonts and ticks based on the audience (e.g., "notebook", "talk", "paper").
    ---
  3. Challenge

    Step 3: Style and Color Your Chart

    Step 3: Customize Bar Colors and Styles

    Styling a chart is more than just aesthetics—color and layout can guide attention, reinforce categories, and make data easier to interpret.

    In this step, you’ll learn how to control the look and feel of your bar charts.

    You’ll apply:

    • Custom fill colors to individual bars
    • Seaborn palettes for categorical data
    • Consistent visual themes using sns.set_style()

    This is where your chart starts looking like something you’d show in a presentation or dashboard.

    What You’ll Learn in This Step

    • Change bar colors in matplotlib using the color and edgecolor parameters
    • Use Seaborn’s built-in color palettes for automatic styling
    • Apply global chart styles using sns.set_style()

    You'll complete all tasks in a Jupyter notebook rather than in standalone .py files.

    Open the Notebook

    • Open the file: step-three.ipynb in the workspace.
    Important: You must run the cell before clicking Validate.
    How to Complete Each Task > * Find the matching **code cell** labeled **Task 3.1**, **Task 3.2**, etc. > * Write your code directly in that cell. > * Run the cell using the **Run** button or `Shift+Enter`. > * Save your progress using the **Save** icon or **File > Save and Checkpoint**. > * You do not need to use the terminal or create extra files—all visual output will appear directly in the notebook.

    Apply Custom Bar Colors in Matplotlib

    By default, matplotlib assigns a single color to all bars. But in many cases, adjusting the fill and border colors can improve visual clarity—especially when comparing categories or highlighting specific data.

    You can customize colors by passing color names or hex values to the color and edgecolor parameters:

    Syntax Examples
    plt.bar(x_values, y_values, color='skyblue', edgecolor='black')
    
    • color: Sets the interior fill of each bar
    • edgecolor: Controls the border color
    • You can also pass a list of colors to apply different shades to each bar
    Common Color Formats
    color="steelblue"         # Named color
    color="#1f77b4"           # Hex code
    color=["skyblue", "orange", "salmon"]  # List of colors for each bar
    edgecolor="black"         # Adds a border around bars
    

    Matplotlib supports over 100 named colors and full hexadecimal RGB codes.

    When working with categorical values (like diagnosis), you can generate a list of colors that matches the number of categories, then pass that list to the color parameters. ---

    Use Seaborn Color Palettes

    When working with categorical data like diagnoses, using a distinct color for each category can make the chart easier to scan and compare.

    Seaborn provides built-in color palettes that automatically assign consistent colors to categories. These palettes work seamlessly with Seaborn’s sns.barplot() function.

    Palette Example with `sns.barplot()`
    import seaborn as sns
    sns.barplot(
        x="diagnosis", 
        y="count", 
        hue="diagnosis",          # Required to assign colors per category
        data=table, 
        palette="pastel", 
        legend=False              # Optional: hides the redundant color legend
    )
    

    Popular Seaborn Palettes
    • "deep" – default
    • "muted" – softer contrast
    • "pastel" – light and gentle tones
    • "dark" – high contrast
    • "colorblind" – accessible for most viewers

    You can preview available palettes with:
    sns.color_palette("pastel")
    
    --- ### Apply a Consistent Theme with Seaborn

    In addition to setting bar colors, you can style the entire chart environment using Seaborn’s set_style() function. This controls things like background gridlines, axis borders, and overall visual tone.

    This helps maintain visual consistency across multiple plots—especially in presentations or reports.

    Available Seaborn Styles
    sns.set_style("whitegrid")  # Recommended for bar charts
    

    Other options:

    • "white" – minimal, no grid
    • "dark" – dark background
    • "darkgrid" – dark background with grid
    • "ticks" – white background with tick borders only

    You typically call sns.set_style() once before plotting and it will persist for all following charts unless explicitly changed.

  4. Challenge

    Step 4: Experiment with Layout Variations

    Step 4: Experiment with Layout Variations in Matplotlib

    Matplotlib supports more than just vertical bar charts. You can rotate axes, stack values, or even create grouped comparisons. In this step, you’ll explore layout variations that help communicate different types of relationships in your data.

    What You’ll Learn in This Step

    • Create a horizontal bar chart using plt.barh()
    • Build a stacked bar chart using the bottom parameter

    You'll complete all tasks in a Jupyter notebook rather than in standalone .py files.

    Open the Notebook

    • Open the file: step-four.ipynb in the workspace.
    Important: You must run the cell before clicking Validate.
    How to Complete Each Task > * Find the matching **code cell** labeled **Task 4.1**, **Task 4.2**, etc. > * Write your code directly in that cell. > * Run the cell using the **Run** button or `Shift+Enter`. > * Save your progress using the **Save icon** or **File > Save and Checkpoint**. > * You do not need to use the terminal or create extra files—all code and output will appear directly in the notebook.
    ### Convert to a Horizontal Layout with `plt.barh()`

    A horizontal bar chart can be more effective than a vertical one—especially when category names are long or when you want to emphasize ranking over raw counts.

    Matplotlib makes this easy by using plt.barh() instead of plt.bar().

    Syntax Overview
    plt.barh(y=categories, width=values)
    
    • y – A list of category labels (appears along the vertical axis)
    • width – The numerical values (bar lengths along the horizontal axis)

    This layout flips the usual orientation:

    • Category names are listed top-to-bottom
    • Values are measured left-to-right

    Create a Stacked Bar Chart Using the bottom Parameter

    A stacked bar chart allows you show multiple values for the same category—layered visually to display sub-totals and totals at once.

    Matplotlib’s plt.bar() supports stacking by setting the bottom parameter. This tells Python where to start each bar, allowing you to stack new values on top of existing ones.

    Basic Syntax
    plt.bar(x=labels, height=group1)
    plt.bar(x=labels, height=group2, bottom=group1)
    

    To use this pattern:

    • Group the dataset by two dimensions (e.g., diagnosis and gender)
    • Plot one group first (e.g., Male)
    • Stack the other on top (e.g., Female) using the bottom argument to align the bars vertically
  5. Challenge

    Step 5: Final Touches and Exporting in Matplotlib

    Step 5: Final Touches and Exporting in Matplotlib

    Polished charts are just as important as accurate ones. After analyzing and visualizing your data, you should be able to:

    • Communicate uncertainty using error bars
    • Eliminate chart clutter like excess spines or borders
    • Export your final chart using plt.savefig() for sharing or documentation

    This step equips you with the tools to finalize your visualization with clarity, precision, and portability.

    What You’ll Learn in This Step

    • Add vertical and horizontal error bars using yerr and xerr
    • Clean up unnecessary chart spines
    • Export your chart using plt.savefig()

    You'll complete all tasks in a Jupyter notebook rather than in standalone .py files.

    Open the Notebook

    • Open the file: step-five.ipynb in the workspace.
    Important: You must run the cell before clicking Validate.
    How to Complete Each Task > * Find the matching code cell labeled **Task 5.1**, **Task 5.2**, etc. > * Write your code directly in that cell. > * Run the cell using the **Run** button or `Shift+Enter`. > * Save your progress using the **Save icon** or **File > Save and Checkpoint**. > * You do not need to use the terminal—all output and file exports are handled within the notebook.
    ### Add Error Bars to Your Bar Chart

    Error bars are used to show variability or uncertainty in your data—such as survey margin of error or confidence intervals.

    In Matplotlib, you can add error bars to bar charts using:

    • yerr= → for vertical bar charts
    • xerr= → for horizontal bar charts

    These parameters accept a single number (same error for all bars) or a list/array of values (custom error for each bar).


    Syntax Breakdown: plt.bar(..., yerr=...) or xerr=...
    # Vertical bar chart with constant error
    plt.bar(x=["A", "B", "C"], height=[10, 15, 8], yerr=2)
    
    # Horizontal bar chart with different errors per bar
    plt.barh(y=["X", "Y", "Z"], width=[5, 7, 4], xerr=[1, 2, 1])
    

    Parameters Explained:

    • x or y: Category labels

    • height or width: Bar size (numerical values)

    • yerr / xerr: Error margins

      • A single number → same error for all bars
      • A list/array → different error per bar
    ### Remove Extra Chart Spines

    Chart spines are the border lines surrounding the plot area. By default, Matplotlib includes all four spines: top, right, left, and bottom.

    In most modern chart designs, the top and right spines are removed to reduce visual clutter and shift the focus toward the data.


    Syntax Breakdown: Removing Spines with plt.gca().spines
    # Access the current Axes
    ax = plt.gca()
    
    # Hide the top and right spines
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    

    What this does:

    • plt.gca() retrieves the current Axes object
    • The spines dictionary allows you to access each border line.
    • Setting .set_visible(False) hides that spine from the plot.
    ### Save Your Chart as a PNG Image

    Once your chart is complete, you may want to share it in reports, presentations, or emails. Matplotlib allows you to export your chart as an image using the savefig() function.

    This ensures that your visualization can be reused outside of the notebook—and that its formatting is preserved exactly as rendered.


    Syntax Breakdown: plt.savefig("filename.png")
    plt.savefig("output_chart.png")
    

    Tips:

    • Always call savefig() before plt.show().
    • Use .png, .jpg, or .pdf as your file extension
    • To avoid overwritting files, give each export a unique name.
  6. Challenge

    Step 6: Get Started with Seaborn for Declarative Plotting

    Step 6: Get Started with Seaborn for Declarative Plotting

    Declarative plotting tools like Seaborn let you build expressive charts with less code. Instead of manually calculating values and drawing each component, you describe what you want to show and Seaborn takes care of the rendering logic.

    In this step, you'll use sns.barplot() to quickly generate charts that summarize key patient metrics.

    What You’ll Learn in This Step

    • Create bar charts using Seaborn’s sns.barplot() function
    • Use the estimator parameter to count or summarize automatically
    • Apply Seaborn’s built-in themes for clean, presentation-ready visuals

    You'll complete all tasks in a Jupyter notebook rather than in standalone .py files.

    Open the Notebook

    • Open the file: step-six.ipynb in the workspace.
    Important: You must run the cell before clicking Validate.
    How to Complete Each Task > * Find the matching **code cell** labeled **Task 6.1**, **Task 6.2**, etc. > * Write your code directly in that cell. > * Run the cell using the **Run** button or `Shift+Enter`. > * Save your progress using the **Save icon** or **File > Save and Checkpoint**. > * You do not need to use the terminal—all output and file exports are handled within the notebook.
    ### Use `sns.barplot()` to Count Categories Automatically

    Seaborn’s sns.barplot() is designed to be declarative: you provide a dataset and column names, and it automatically computes the necessary summaries and draws the chart.

    Unlike plt.bar(), you don’t need to manually count or aggregate values. Just pass a categorical column for the x-axis and a numeric column for the y-axis—Seaborn handles the rest.


    Syntax Example: Counting by Category
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.barplot(x="diagnosis", y="patient_id", data=df, estimator=len)
    plt.show()
    
    • x: Categorical grouping column (e.g., "diagnosis")
    • y: Numeric column to summarize (e.g., "patient_id")
    • estimator: Function to apply (such as len, sum, or mean)
    • data: Source DataFrame
    ### Add Axis Labels and a Title to Your Seaborn Chart

    In this task, you'll improve the readability of your Seaborn bar chart by adding axis labels and a title using matplotlib.pyplot.

    Even though Seaborn handles much of the chart layout, labeling remains your responsibility. You’ll use standard plt functions to make the chart self-explanatory and presentation-ready.


    Labeling with matplotlib.pyplot
    plt.xlabel("Diagnosis")
    plt.ylabel("Patient Count")
    plt.title("Number of Patients by Diagnosis")
    
    • xlabel() – Adds a label beneath the x-axis
    • ylabel() – Adds a label beside the y-axis
    • title() – Adds a descriptive chart title

    Add Axis Labels and a Title to Your Seaborn Chart

    In this task, you'll improve the readability of your Seaborn bar chart by adding axis labels and a title using matplotlib.pyplot.

    Even though Seaborn handles much of the chart layout, labeling remains your responsibility. You’ll use standard plt functions to make the chart self-explanatory and presentation-ready.


    Labeling with matplotlib.pyplot
    plt.xlabel("Diagnosis")
    plt.ylabel("Number of Patients")
    plt.title("Number of Patients by Diagnosis")
     ### Apply a Colorblind-Friendly Palette with Seaborn
    
    Color plays a crucial role in how your charts are interpreted. Using accessible palettes—such as Seaborn’s `"colorblind"` palette—ensures your visualizations are inclusive and easy to understand for all audiences.
    
    In this task, you’ll apply a high-contrast, colorblind-safe palette to your chart using`sns.color_palette("colorblind")` 
    
    ---
    
    <details>
    <summary><strong>Using a Colorblind-Safe Palette</strong></summary>
    
    ```python
    import seaborn as sns
    sns.set_palette("colorblind")
    

    This command updates the global color cycle, affecting all subsequent Seaborn and Matplotlib charts.

  7. Challenge

    Step 7: Advanced Seaborn Features

    Step 7: Advanced Seaborn Features and Export

    Grouped bar charts are an effective way to compare multiple categories side by side. Seaborn makes this easy using the hue parameter, which segments each bar group visually without manual layout logic.

    In this step, you’ll build grouped bar charts using Seaborn’s high-level plotting tools and explore how to control orientation and spacing.

    What You’ll Learn in This Step

    • Use the hue parameter in sns.barplot() to segment bars by category
    • Convert grouped bars to horizontal layout using orient="h"
    • Control spacing between grouped bars using dodge=False

    You'll complete all tasks in a Jupyter notebook rather than in standalone .py files.

    Open the Notebook

    • Open the file: step-seven.ipynb in the workspace.
    Important: You must save the notebook before clicking Validate.
    How to Complete Each Task > * Find the matching **code cell** labeled **Task 7.1**, **Task 7.2**, etc. > * Write your code directly in that cell. > * Run the cell using the **Run** button or `Shift+Enter`. > * Save your progress using the **Save icon** or **File > Save and Checkpoint**. > > You do not need to use the terminal—all output and file exports are handled within the notebook.
    ### Use the `hue` Parameter to Create Grouped Bar Charts

    When you want to compare subgroups within a main category—for example, comparing male and female satisfaction scores within each hospital—Seaborn’s hue parameter handles this automatically.

    Instead of reshaping your data manually (as you would in Matplotlib), you simply specify an additional categorical column. Seaborn will segment the bars and generate a grouped layout by default.


    Syntax Example: Grouped Bars with `hue`
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.barplot(x="hospital", y="satisfaction", hue="gender", data=df)
    plt.title("Satisfaction by Hospital and Gender")
    plt.xticks(rotation=45)
    plt.show()
    
    • x: Main grouping column (e.g., "hospital")
    • y: Numeric metric (e.g., "satisfaction")
    • hue: Subgroup column (e.g., "gender")
    • data: DataFrame with tidy-format input

    You can produce multi-dimensional insights with just a single line of code—this is great for comparing patterns across multiple variables.

    ### Change Orientation with `orient="h"` for Horizontal Grouped Bars

    Sometimes, horizontal bar charts offer better readability—especially when category labels are long or when comparing smaller differences in values.

    Seaborn supports horizontal grouped bars by setting the orient="h" parameter in sns.barplot(). This flips the chart so categories appear on the y-axis and values extend along the x-axis.


    Syntax Example: Horizontal Grouped Bars
    sns.barplot(
        y="hospital",
        x="satisfaction",
        hue="gender",
        data=df,
        orient="h"
    )
    
    • x / y: Swapping these flips the chart’s direction
    • orient='h': Explicitly sets horizontal orientation
    • hue: Controls subgroup color grouping

    This layout is helpful when your category names are too crowded or when a left-to-right comparison feels more natural in context.

    ### Control Group Spacing with `dodge=False`

    By default, Seaborn spaces grouped bars side by side to clearly show distinctions between subgroups. But sometimes, especially with many categories, tighter spacing is more readable.

    The dodge parameter controls this behavior:

    • dodge=True (default): Separates each subgroup into distinct bars.
    • dodge=False: Overlays the bars for each group—useful for a more compact look or when the subgroups are closely related.

    This is especially effective when you're comparing relative totals rather than exact subgroup differences.


    Syntax Example: Disabling Group Spacing
    sns.barplot(
        x="hospital",
        y="satisfaction",
        hue="gender",
        data=df,
        dodge=False
    )
    
    • dodge=False: Merges the bars of each group into a single stack or overlay.
    • Combine with transparency (alpha) or edge outlines to preserve clarity.

    This technique is helpful when visual space is limited, or when the emphasis is on total bar height rather than exact subgroup breakdown.

    Customize or Remove the Legend for Grouped Bar Charts

    Grouped bar charts include a legend by default to indicate the meaning of colors assigned via hue. In some contexts, however, the legend may be redundant or better placed elsewhere.

    Seaborn and Matplotlib give you full control over the legend’s visibility, position, and appearance using plt.legend() or ax.legend().

    You can:

    • Remove the legend completely with plt.legend().remove().
    • Move it to the top, bottom, or side using loc parameter.
    • Add a title to clarify what’s being grouped.

    Syntax Example: Legend Control
    sns.barplot(x="hospital", y="satisfaction", hue="gender", data=df)
    plt.title("Satisfaction by Gender")
    plt.legend(title="Gender", loc="upper right")
    

    To remove the legend:

    plt.legend().remove()
    

    Managing the legend helps focus the chart on what matters most, especially when the visual grouping is self-explanatory or already labeled elsewhere.

  8. Challenge

    Step 8: Finalize and Export Seaborn Charts

    Step 8: Finalize and Export Seaborn Charts

    As you wrap up your grouped bar chart, it's time to polish and export your work.

    In this step, you'll:

    • Remove unnecessary chart borders (called spines) for a cleaner look
    • Save your final Seaborn chart as a static image using plt.savefig()

    These steps help ensure your chart is presentation-ready for reports, slides, or dashboards.

    What You’ll Learn in This Step

    • Remove visual clutter using sns.despine()
    • Export your chart to a .png file with plt.savefig()

    You'll complete all tasks in a Jupyter notebook rather than in standalone .py files.

    Open the Notebook

    • Open the file: step-eight.ipynb in the workspace.
    Important: You must run the cell before clicking Validate.
    How to Complete Each Task > * Find the matching **code cell** labeled **Task 8.1**, **Task 8.2**, etc. > * Write your code directly in that cell. > * Run the cell using the **Run** button or `Shift+Enter`. > * Save your progress using the **Save icon** or **File > Save and Checkpoint**. > * You do not need to use the terminal—all output and file exports are handled within the notebook.
    ### Remove Visual Clutter with `sns.despine()`

    By default, Seaborn charts include all four spines (outer borders). However, the top and right edges often don’t add value. Removing them can make your chart feel cleaner and more modern—especially when preparing visuals for stakeholders or reports.

    The sns.despine() function removes unnecessary spines with a single line of code.


    Syntax Example: Remove Chart Spines
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.barplot(x="hospital", y="satisfaction", hue="gender", data=df)
    plt.title("Cleaned-Up Grouped Chart")
    sns.despine()
    plt.show()
    
    • sns.despine() removes top and right borders by default.
    • Use it after creating the plot, but before saving or displaying it.
    ### Save Your Chart with `plt.savefig()`

    Once you’ve created a polished chart, the final step is to export it for use outside the notebook. Matplotlib’s plt.savefig() function saves the current figure as an image file—perfect for reports, presentations, or emails.

    You can specify the file format, size, resolution, and export location.


    Syntax Example: Exporting to PNG
    plt.savefig("satisfaction_by_hospital.png", dpi=300, bbox_inches="tight")
    
    • "satisfaction_by_hospital.png": Output file name (can include path)
    • dpi=300: Sets resolution to 300 dots per inch (suitable for print)
    • bbox_inches="tight": Crops extra whitespace around the image
    ## You've Completed the Lab!

    Great job! You’ve now built a complete, presentation-ready grouped bar chart using Seaborn.

    Here’s what you accomplished:

    • Used the hue parameter to group data visually
    • Switched between vertical and horizontal layouts for better readability
    • Controlled spacing with dodge=False and cleaned up visuals using sns.despine()
    • Customized and removed legends to improve clarity
    • Exported your final chart as a high-quality .png file using plt.savefig()

    These techniques are essential for creating insightful, professional-grade visualizations that communicate data clearly and effectively.

What's a lab?

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Provided environment for hands-on practice

We will provide the credentials and environment necessary for you to practice right within your browser.

Guided walkthrough

Follow along with the author’s guided walkthrough and build something new in your provided environment!

Did you know?

On average, you retain 75% more of your learning if you get time for practice.