FormulaCamp
Completed
15. Python in Excel and AI · pandas and Python Charts · 15 min

4. Charts: Matplotlib and Seaborn

Lesson 4 of 6
    Lesson theory

    Code in a =PY() cell can return a picture. Excel shows it as an object in the cell; from the Python menu you can move it onto the sheet, above the grid, and resize it.

    import matplotlib.pyplot as plt
    df = xl("A1:B13", headers=True)
    plt.bar(df["Month"], df["Sales"])
    plt.title("Sales by Month")
    plt.ylabel("Sales, $K")

    Seaborn is built on top of Matplotlib and groups the data for you:

    import seaborn as sns
    df = xl("A1:C200", headers=True)
    sns.barplot(data=df, x="City", y="Amount", estimator="sum")   # bars = sum by city
    sns.histplot(df["Amount"], bins=10)                           # distribution of order sizes
    sns.boxplot(data=df, x="City", y="Amount")                    # spread and outliers
    • plt.bar draws columns, plt.plot a line, and plt.scatter a scatter plot;
    • in sns.barplot, the default estimator is the mean, not the sum. A common mistake is a chart labeled "Revenue" that actually shows the average order;
    • a histogram and a box plot show what ordinary Excel charts don't without extra setup: the distribution and outliers;
    • a chart from Python is a static picture. It recalculates with the cell when the data changes, but you can't click its points or restyle it with the mouse the way you can with an Excel chart.

    Test yourself

    1. What does sns.barplot(data=df, x="City", y="Amount") draw without the estimator parameter?
    2. Which chart shows how order sizes are distributed across ranges?
    3. What is sns.boxplot useful for?
    4. How does a Python in Excel chart differ from a regular Excel chart?
    5. Which line adds a title to a Matplotlib chart?