# Module 12: Data Visualization with Pandas ## Learning Objectives By the end of this module, you will be able to: - Generate quick exploratory plots with the Pandas `.plot()` accessor - Customise chart appearance, labels, titles, and legends - Create line charts, scatter plots, histograms, bar charts, and box plots - Build pie charts and area charts for compositional data - Combine Pandas plotting with Matplotlib for fine-grained control - Use subplots to compare multiple visualisations --- ```{note} Visualisation is the most effective way to communicate patterns, outliers, and trends in your data. Pandas integrates directly with Matplotlib, enabling rapid plotting from DataFrames without extensive boilerplate. ``` ## Matplotlib Setup Pandas plotting is built on top of Matplotlib. Always import it for customisation. ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt # Display plots inline (Jupyter) %matplotlib inline # Style configuration plt.style.use("seaborn-v0_8-darkgrid") ``` ```{tip} Set `plt.style.use("ggplot")` or `"seaborn-v0_8-darkgrid"` early in your notebook for consistently styled plots. Explore all available styles with `print(plt.style.available)`. ``` ## Line Charts Line charts are ideal for time series and trends. ```python # Sample time series data np.random.seed(42) dates = pd.date_range("2024-01-01", periods=100, freq="D") ts_df = pd.DataFrame({ "Sales": np.cumsum(np.random.randn(100) * 10 + 50), "Visitors": np.cumsum(np.random.randn(100) * 5 + 30), }, index=dates) # Basic line plot ts_df["Sales"].plot( title="Daily Sales Trend", xlabel="Date", ylabel="Sales ($)", figsize=(10, 5), grid=True, ) plt.show() ``` ### Multiple lines ```python # Plot multiple columns ts_df.plot( title="Sales and Visitors Over Time", xlabel="Date", ylabel="Value", figsize=(12, 5), grid=True, alpha=0.8, ) plt.show() ``` ```{warning} When plotting multiple series with very different scales, consider using twin axes or separate subplots to avoid misleading visual comparisons. ``` ### Customising line styles ```python ts_df["Sales"].plot( style="r--", # Red dashed line linewidth=2, marker="o", markersize=4, alpha=0.8, label="Revenue", ) plt.title("Sales with Markers") plt.xlabel("Date") plt.ylabel("Sales ($)") plt.legend() plt.grid(True) plt.show() ``` ## Scatter Plots Scatter plots reveal relationships between two numeric variables. ```python df = pd.DataFrame({ "Advertising_Spend": np.random.uniform(1000, 10000, 200), "Sales": np.random.uniform(5000, 50000, 200), "Region": np.random.choice(["North", "South", "East", "West"], 200), }) # Basic scatter df.plot.scatter( x="Advertising_Spend", y="Sales", title="Advertising Spend vs Sales", figsize=(8, 6), alpha=0.6, ) plt.show() ``` ### Colour-coded scatter ```python # Colour by region colors = {"North": "blue", "South": "red", "East": "green", "West": "orange"} df["Color"] = df["Region"].map(colors) df.plot.scatter( x="Advertising_Spend", y="Sales", c=df["Color"], title="Advertising Spend vs Sales (by Region)", figsize=(8, 6), alpha=0.7, ) plt.show() ``` ## Histograms Histograms show the distribution of numeric data. ```python # Basic histogram df["Sales"].plot.hist( bins=20, title="Sales Distribution", figsize=(8, 5), edgecolor="black", alpha=0.7, ) plt.xlabel("Sales ($)") plt.show() ``` ### Multiple histograms ```python # Overlaid histograms df[df["Region"] == "North"]["Sales"].plot.hist( bins=15, alpha=0.5, label="North", color="blue" ) df[df["Region"] == "South"]["Sales"].plot.hist( bins=15, alpha=0.5, label="South", color="red" ) plt.title("Sales Distribution by Region") plt.xlabel("Sales ($)") plt.legend() plt.show() ``` ### Density plot (KDE) ```python df["Sales"].plot.kde( title="Sales Density Estimate", figsize=(8, 5), linewidth=2, ) plt.xlabel("Sales ($)") plt.show() ``` ```{tip} Use KDE (Kernel Density Estimate) plots alongside histograms to get a smooth estimate of the probability distribution. The bandwidth parameter controls smoothness. ``` ## Bar Charts Bar charts compare quantities across categories. ```python # Aggregate data for bar chart region_sales = df.groupby("Region")["Sales"].agg(["sum", "mean"]) # Bar plot of total sales by region region_sales["sum"].plot.bar( title="Total Sales by Region", figsize=(8, 5), color=["blue", "red", "green", "orange"], edgecolor="black", ) plt.ylabel("Total Sales ($)") plt.xticks(rotation=0) plt.show() ``` ### Horizontal bar chart ```python region_sales["mean"].plot.barh( title="Average Sales by Region", figsize=(8, 5), color="teal", edgecolor="black", ) plt.xlabel("Average Sales ($)") plt.show() ``` ### Grouped bar chart ```python # Create categorical data bar_df = pd.DataFrame({ "Product": ["A", "B", "C", "D"], "Q1": [100, 150, 120, 90], "Q2": [110, 160, 130, 95], "Q3": [130, 140, 125, 100], "Q4": [140, 170, 140, 105], }).set_index("Product") # Grouped bar bar_df.plot.bar( title="Quarterly Sales by Product", figsize=(10, 6), edgecolor="black", ) plt.ylabel("Sales ($)") plt.xticks(rotation=0) plt.legend(title="Quarter") plt.show() ``` ### Stacked bar chart ```python bar_df.plot.bar( stacked=True, title="Quarterly Sales by Product (Stacked)", figsize=(10, 6), edgecolor="black", ) plt.ylabel("Sales ($)") plt.xticks(rotation=0) plt.legend(title="Quarter") plt.show() ``` ## Box Plots Box plots summarise distribution through quartiles and highlight outliers. ```python # Basic box plot df.boxplot( column="Sales", by="Region", figsize=(8, 6), grid=True, ) plt.title("Sales Distribution by Region") plt.suptitle("") # Remove automatic suptitle plt.ylabel("Sales ($)") plt.show() ``` ### Using Pandas `.plot.box()` ```python df[["Sales", "Advertising_Spend"]].plot.box( title="Sales and Advertising Distribution", figsize=(8, 6), ) plt.ylabel("Value ($)") plt.show() ``` ```{note} Box plots show the median (centre line), interquartile range (box), whiskers (1.5× IQR), and outliers (points beyond whiskers). They are excellent for comparing distributions across groups. ``` ## Pie Charts Pie charts show proportions of a whole. ```python # Market share by region region_totals = df.groupby("Region")["Sales"].sum() region_totals.plot.pie( title="Sales Distribution by Region", figsize=(7, 7), autopct="%1.1f%%", startangle=90, explode=(0.05, 0.05, 0.05, 0.05), shadow=True, ) plt.ylabel("") # Remove default ylabel plt.show() ``` ```{warning} Pie charts work well for 3-5 categories. For more categories, use a bar chart instead — humans are poor at comparing angles from many slices. ``` ## Area Charts Area charts emphasise magnitude over time. ```python # Cumulative area chart ts_df.plot.area( title="Cumulative Sales and Visitors", figsize=(10, 6), alpha=0.5, ) plt.ylabel("Value") plt.show() ``` ### Stacked area for composition ```python # Composition data composition = pd.DataFrame({ "Product A": np.random.randint(100, 200, 30), "Product B": np.random.randint(50, 150, 30), "Product C": np.random.randint(20, 100, 30), }, index=pd.date_range("2024-01-01", periods=30, freq="D")) composition.plot.area( title="Daily Sales Composition", figsize=(10, 6), alpha=0.7, ) plt.ylabel("Sales ($)") plt.show() ``` ## Subplots ### Automatic subplots per column ```python ts_df[["Sales", "Visitors"]].plot( subplots=True, title=["Sales Trend", "Visitor Trend"], figsize=(10, 8), layout=(2, 1), sharex=True, ) plt.tight_layout() plt.show() ``` ### Manual subplots with Matplotlib ```python fig, axes = plt.subplots(2, 2, figsize=(12, 10)) # Top-left: Histogram df["Sales"].plot.hist(ax=axes[0, 0], bins=20, edgecolor="black", alpha=0.7) axes[0, 0].set_title("Sales Distribution") axes[0, 0].set_xlabel("Sales ($)") # Top-right: Box plot df.boxplot(column="Sales", by="Region", ax=axes[0, 1]) axes[0, 1].set_title("Sales by Region") axes[0, 1].set_suptitle("") # Bottom-left: Bar chart region_sales["sum"].plot.bar(ax=axes[1, 0], color="steelblue", edgecolor="black") axes[1, 0].set_title("Total Sales by Region") axes[1, 0].set_ylabel("Sales ($)") axes[1, 0].tick_params(axis="x", rotation=0) # Bottom-right: Scatter df.plot.scatter(ax=axes[1, 1], x="Advertising_Spend", y="Sales", alpha=0.6) axes[1, 1].set_title("Advertising vs Sales") plt.tight_layout() plt.show() ``` ## Saving Figures ```python fig, ax = plt.subplots(figsize=(10, 5)) ts_df["Sales"].plot(ax=ax, linewidth=2, color="darkblue") ax.set_title("Daily Sales Trend") ax.set_xlabel("Date") ax.set_ylabel("Sales ($)") ax.grid(True) # Save to file plt.savefig("sales_trend.png", dpi=300, bbox_inches="tight") plt.savefig("sales_trend.pdf", format="pdf", bbox_inches="tight") plt.show() ``` ```{tip} Always use `bbox_inches="tight"` when saving to avoid clipped labels. Use 300 DPI for print quality and consider SVG/PDF for scalable vector graphics. ``` ## Complete Example: Exploratory Dashboard ```python # Generate realistic dataset np.random.seed(42) n = 500 dashboard = pd.DataFrame({ "Date": pd.date_range("2024-01-01", periods=n, freq="D"), "Product": np.random.choice(["Widget", "Gadget", "Doohickey"], n), "Region": np.random.choice(["North", "South", "East", "West"], n), "Sales": np.round(np.random.uniform(10, 500, n), 2), "Quantity": np.random.randint(1, 20, n), "Rating": np.round(np.random.uniform(1, 5, n), 1), }) fig, axes = plt.subplots(2, 3, figsize=(15, 10)) # 1. Sales over time (weekly) weekly = dashboard.set_index("Date").resample("W")["Sales"].sum() weekly.plot(ax=axes[0, 0], title="Weekly Sales Trend", color="steelblue") axes[0, 0].set_ylabel("Sales ($)") # 2. Sales by product dashboard.groupby("Product")["Sales"].sum().plot.bar( ax=axes[0, 1], title="Sales by Product", color="coral", edgecolor="black" ) axes[0, 1].tick_params(axis="x", rotation=0) # 3. Sales distribution dashboard["Sales"].plot.hist( ax=axes[0, 2], bins=25, title="Sales Distribution", edgecolor="black", alpha=0.7 ) # 4. Sales by region (box plot) dashboard.boxplot(column="Sales", by="Region", ax=axes[1, 0]) axes[1, 0].set_title("Sales by Region") axes[1, 0].set_suptitle("") # 5. Quantity vs Sales scatter dashboard.plot.scatter(ax=axes[1, 1], x="Quantity", y="Sales", alpha=0.5, color="green") axes[1, 1].set_title("Quantity vs Sales") # 6. Rating distribution dashboard["Rating"].plot.hist( ax=axes[1, 2], bins=10, title="Rating Distribution", edgecolor="black", alpha=0.7, color="purple" ) plt.tight_layout() plt.show() ``` ## Summary - Pandas `.plot()` accessor provides quick visualisations for line, bar, scatter, histogram, box, pie, and area charts - Customise with Matplotlib functions (`plt.title()`, `plt.xlabel()`, `plt.legend()`, etc.) - Use `figsize` and `subplots` for multi-chart layouts - Colour, alpha, and edgecolor parameters enhance visual clarity - Save figures with `plt.savefig()` for reports and presentations - Box plots and histograms reveal distribution characteristics - Scatter plots uncover relationships between numeric variables - Bar charts and pie charts compare categorical data ## Exercises Using this dataset: ```python import pandas as pd import numpy as np import matplotlib.pyplot as plt np.random.seed(42) df = pd.DataFrame({ "Department": np.random.choice(["Sales", "Marketing", "Engineering", "HR"], 300), "Salary": np.round(np.random.uniform(40000, 120000, 300), 0), "Experience": np.random.randint(1, 20, 300), "Performance": np.round(np.random.uniform(1, 5, 300), 1), "Projects": np.random.randint(1, 10, 300), }) ``` 1. Create a histogram of Salary with 25 bins, add a title and axis labels 2. Create a box plot comparing Salary across Departments 3. Create a scatter plot of Experience vs Salary, colour-coded by Department 4. Create a bar chart showing average Performance by Department 5. Create a 2×2 subplot layout combining a histogram, box plot, scatter plot, and bar chart 6. Save the combined figure as `employee_analysis.png` at 300 DPI ## Further Reading - [Pandas Plotting Documentation](https://pandas.pydata.org/docs/user_guide/visualization.html) - [Matplotlib Documentation](https://matplotlib.org/stable/contents.html) - [Matplotlib Gallery](https://matplotlib.org/stable/gallery/index.html)