Module 1, topic 12, week 6, Thursday
Data visualization: Matplotlib and Seaborn basics
The first chart, titles and styles, the main chart types, charts from the columns of a table, and Seaborn from small lists to heatmaps
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example and the 15 solved problems. Run a cell to see its chart.
topic-12-data-visualization-matplotlib-seaborn.ipynb, 88 KB
Practice notebook
The 15 practice problems as one notebook that continues from a setup cell, with a hint and a hidden solution for each.
topic-12-practice.ipynb, 27 KB
Data file: the orders
300 orders of an invented online shop in 2025, the same file as in the last two lessons.
orders.csv, 14 KB
Data file: the customers
One row for every customer of the shop: age, gender and the year of joining. Used for charts of two joined tables.
customers.csv, 1 KB
Introduction: seeing data
A beginner-friendly guide to drawing charts in Python. A table of 300 rows is hard to read, but one good chart of it is understood in a few seconds. This guide starts with Matplotlib, the basic drawing library of Python: first a line through a few numbers, then titles, colours and legends, then every chart type you really need. After that the same charts are drawn from the columns of our data. The second half is Seaborn, a library built on Matplotlib: first the same charts from the same small lists, then charts straight from a table in one line. It starts from the simplest examples and gets harder step by step. Then it walks through 15 solved problems from easy to medium-hard. At the end there are practice problems.
You should already know the last lessons: NumPy arrays, reading a file with pandas, choosing columns, groupby, value_counts and merge.
The data files. The charts of real data use the same files as the last two lessons: orders.csv (300 orders of a small online shop in 2025) and customers.csv (one row for every customer). Put both files into the same folder as your notebook.
On this page both files are already there for every example. You can look at them below and in Part 8, and download them from the box at the top.
The data file: orders.csv
300 orders, 8 columns. A cell marked "empty" has no value in the file: pandas shows it as NaN.
Loading the table ...
What you will learn
- 1.The first chart with
plt.plot, and the three things every chart needs: a title and two axis labels - 2.Colours, line styles, markers, legends, grids, the size of a chart and saving it
- 3.The main chart types and the question each one answers: line, bar, histogram, scatter, box plot, pie
- 4.Several charts in one figure with
plt.subplots - 5.Charts from the columns of a table: summarise first, then draw
- 6.Seaborn: the same charts from lists, then straight from a table:
countplot,barplot,histplot,boxplot,scatterplot,lineplot - 7.Groups in colour with
hue,violinplot,heatmap,regplotandpairplot - 8.How to choose the right chart for a question
- 9.15 solved problems and practice problems
1The first chart
1.1What Matplotlib is
Matplotlib is the library that draws charts. Almost every other chart library of Python, Seaborn and the plot method of pandas included, uses it underneath. The part we need is called pyplot, and everybody imports it with the short name plt:
import matplotlib.pyplot as pltIn Anaconda and in Google Colab it is already installed.
1.2A line through four numbers
import matplotlib.pyplot as plt
plt.plot([3, 5, 4, 8])
plt.show()
Change it and run: add a fifth number to the list. The line gets one more point.
Two lines of code make a chart:
plt.plot(...)draws the values as points and joins them with a line.plt.show()shows the finished chart and closes it: what you draw after it starts a new chart. Write it as the last line of every chart.
The list has only the heights (the y values). Matplotlib used the positions 0, 1, 2, 3 for the horizontal axis (the x values), the same numbers as the indexes of the list.
1.3x and y
Usually you give both: first the x values, then the y values.
days = [1, 2, 3, 4, 5]
visitors = [120, 135, 128, 160, 190]
plt.plot(days, visitors)
plt.show()
Change it and run: change the last number of visitors to 100. The line turns down.
The first point is (1, 120), the second is (2, 135), and so on. The two lists must have the same length: every x needs its y.
1.4A title and axis labels
The chart above does not say what it shows. A reader should never have to guess, so every chart gets a title and a label for each axis.
plt.plot(days, visitors)
plt.title("Visitors of the shop")
plt.xlabel("Day")
plt.ylabel("Visitors")
plt.show()
Change it and run: change the title to "Visitors in the first week".
The order is always the same: draw, describe, show. Every plt. line between the drawing and plt.show() adds something to the same chart.
- 1The title:
plt.title("Visitors of the shop") - 2The label of the y axis:
plt.ylabel("Visitors") - 3The label of the x axis:
plt.xlabel("Day") - 4The line through the values:
plt.plot(days, visitors) - 5A marker at a real value:
marker="o" - 6The ticks, the marks of an axis:
plt.xticks(...)
1.5A chart from NumPy arrays
Matplotlib works with arrays in the same way as with lists. With np.linspace and one calculation on the whole array you can draw the curve of a formula.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 5, 50)
y = x ** 2
print(x[:4])
print(y[:4])
plt.plot(x, y)
plt.title("y = x squared")
plt.xlabel("x")
plt.ylabel("y")
plt.show()Output
[0. 0.10204082 0.20408163 0.30612245] [0. 0.01041233 0.04164931 0.09371095]

Change it and run: change 50 to 5 in np.linspace. Now you see the corners of the curve.
x has 50 values from 0 to 5, and y has the square of each. The curve looks smooth, but it is 50 points joined by short straight lines. With np.linspace(0, 5, 5) you would see the corners.
Try it yourself
values as a line with circle markers. Add the title Powers of two and a label for each axis.Show a hint
plt.plot(values, marker="o"). With one list the x values are the positions 0 to 4.Show the solution
import matplotlib.pyplot as plt
values = [2, 4, 8, 16, 32]
plt.plot(values, marker="o")
plt.title("Powers of two")
plt.xlabel("Position")
plt.ylabel("Value")
plt.show()
2Making a chart readable
2.1Colour, line style and marker
plt.plot has parameters for the look of the line.
import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5]
visitors = [120, 135, 128, 160, 190]
plt.plot(days, visitors, color="teal", linestyle="--", marker="o", linewidth=2)
plt.title("Visitors of the shop")
plt.xlabel("Day")
plt.ylabel("Visitors")
plt.show()
Change it and run: use color="tomato", linestyle=":" and marker="s".
| Parameter | What it changes | Common values |
|---|---|---|
color | the colour | "teal", "tomato", "gray", "black", "orange", "green" |
linestyle | the kind of line | "-" solid, "--" dashed, ":" dotted |
marker | the sign at every point | "o" circle, "s" square, "^" triangle |
linewidth | the thickness | a number, for example 2 |
A marker is useful when there are few points: the reader sees where the real values are.
Choose the look of the line.
color
linestyle
marker
plt.plot(days, visitors, color="teal", linestyle="--", marker="o")
The numbers do not change, only the look. Use a different style when a chart has several lines, and a marker when there are only a few points.
2.2Several lines and a legend
Every plt.plot call adds one more line to the same chart. Give each line a label, and plt.legend() shows a small box that says which line is which.
baku = [120, 135, 128, 160, 190]
ganja = [80, 95, 90, 110, 105]
plt.plot(days, baku, marker="o", label="Baku")
plt.plot(days, ganja, marker="o", label="Ganja")
plt.title("Visitors of two shops")
plt.xlabel("Day")
plt.ylabel("Visitors")
plt.legend()
plt.show()
Change it and run: remove plt.legend(). Which line is which shop?
Matplotlib chooses a different colour for every line. Without plt.legend() the labels are not shown.
2.3A grid and the size of the chart
plt.figure(figsize=(8, 3))
plt.plot(days, visitors, marker="o")
plt.title("Visitors of the shop")
plt.xlabel("Day")
plt.ylabel("Visitors")
plt.grid(True)
plt.show()
Change it and run: change figsize to (4, 4), then to (10, 2).
plt.figure(figsize=(8, 3))starts a new chart that is 8 wide and 3 high (in inches). Write it before the drawing. Without it the size is 6.4 by 4.8.plt.grid(True)draws light lines, so values are easier to read.
2.4The limits and the ticks of the axes
Matplotlib chooses the limits of the axes from the data. You can set them yourself.
plt.plot(days, visitors, marker="o")
plt.title("Visitors of the shop")
plt.xlabel("Day")
plt.ylabel("Visitors")
plt.ylim(0, 200)
plt.xticks(days, ["Mon", "Tue", "Wed", "Thu", "Fri"])
plt.show()
Change it and run: change plt.ylim(0, 200) to plt.ylim(100, 200). The same numbers look like a faster growth.
plt.ylim(0, 200)makes the vertical axis go from 0 to 200 (plt.xlimdoes the same for the horizontal axis). Compare with the chart before: when the axis starts at 0, the growth looks smaller. Both charts are correct, but they give a different feeling, so choose the limits honestly.plt.xticks(positions, names)says where the marks of the axis are and what is written there.
2.5Saving a chart as a picture
plt.plot(days, visitors, marker="o")
plt.title("Visitors of the shop")
plt.savefig("visitors.png")
plt.show()
plt.savefig("visitors.png") writes the chart into a file next to your notebook. Write it before plt.show(): after show the chart is finished and an empty picture would be saved.
Try it yourself
sales. Draw them as a dashed line in a colour of your choice, with the title Sales and both axis labels.Show a hint
plt.plot(days, sales, linestyle="--", color="tomato"). plt.xticks(days) writes only the whole days on the axis.Show the solution
import matplotlib.pyplot as plt
days = [1, 2, 3, 4]
sales = [15, 18, 14, 22]
plt.plot(days, sales, linestyle="--", color="tomato")
plt.title("Sales")
plt.xlabel("Day")
plt.ylabel("Sales")
plt.xticks(days)
plt.show()
3The main chart types
A chart type is not chosen by taste. Each type answers one kind of question. This part shows the six types you need, each with a small list or array.
| Chart | The question it answers |
|---|---|
| Line | How does a value change over time (or along an order)? |
| Bar | How do a few groups compare? |
| Histogram | How are the values of one column spread: where are most of them? |
| Scatter | Do two number columns move together? |
| Box plot | Where is the middle, how wide is the spread, are there unusual values? |
| Pie | What share of the whole does each group have (only for 2 to 4 groups)? |
You already know the line chart. Use it when the x axis has an order: days, months, years, steps.
3.1Bar chart: comparing groups
import matplotlib.pyplot as plt
cities = ["Baku", "Ganja", "Shaki", "Quba"]
orders = [128, 54, 10, 30]
plt.bar(cities, orders, color="teal")
plt.title("Orders by city")
plt.ylabel("Orders")
plt.show()
Change it and run: add a fifth city, Sumqayit with 48 orders, to both lists.
plt.bar(names, heights) draws one bar for every group. The height of a bar is its value, so the eye compares the groups at once. A line would be wrong here: cities have no order, and a line between Baku and Ganja would mean nothing.
When the names are long or there are many groups, turn the bars: plt.barh draws horizontal bars.
cities = ["Shaki", "Quba", "Ganja", "Baku"]
orders = [10, 30, 54, 128]
plt.barh(cities, orders, color="teal")
plt.title("Orders by city")
plt.xlabel("Orders")
plt.show()
Change it and run: change the order of the two lists so that Baku is at the bottom.
barh draws the first group at the bottom. Sorted bars are much easier to read than bars in a random order.
3.2Histogram: how the values are spread
A histogram takes one list of numbers. It cuts the range of the values into equal intervals (called bins) and draws a bar for each: the height says how many values fall into this interval.
grades = [55, 62, 64, 68, 70, 71, 73, 74, 75, 76, 78, 79, 80, 82, 83, 85, 88, 90, 94, 98]
plt.hist(grades, bins=5, color="teal", edgecolor="white")
plt.title("Exam grades of 20 students")
plt.xlabel("Grade")
plt.ylabel("Students")
plt.show()
Change it and run: change bins=5 to bins=10, then to bins=2.
The grades go from 55 to 98, and bins=5 cuts this range into 5 intervals. Most students are in the middle, between about 72 and 81, and few are at the two ends. edgecolor="white" draws a thin line between the bars.
A histogram looks like a bar chart, but it is a different thing:
| Bar chart | Histogram | |
|---|---|---|
| What is on the x axis | groups (names) | intervals of numbers |
| What you give | names and one value for each | one long list of numbers |
| The question | How do groups compare? | Where are most of the values? |
The number of bins changes the picture. Too few bins hide the shape, too many make it noisy. Try 5, 10 and 20 and keep the one that shows the shape best.
The same 20 grades, cut into a different number of bins.
bins
plt.hist(grades, bins=5)
Every bin is 8.6 wide: the first one goes from 55 to 63.6. The shape is clear: few students at both ends, most in the middle.
3.3Scatter chart: two number columns together
A scatter chart draws one point for every pair of values. It shows whether two things move together.
hours = [1, 2, 2, 3, 4, 5, 5, 6, 7, 8]
grade = [52, 55, 61, 64, 70, 68, 77, 80, 85, 91]
plt.scatter(hours, grade, color="teal")
plt.title("Study hours and exam grade")
plt.xlabel("Hours of study")
plt.ylabel("Grade")
plt.show()
Change it and run: add a student who studied 8 hours and got 50. One point is now far from the others.
Every point is one student. The points go up from left to right: students who studied more got higher grades. If the points were a round cloud without direction, the two values would have nothing to do with each other.
The points are not joined with a line, because they have no order: each point is a separate student.
3.4Box plot: middle, spread and unusual values
A box plot shows a list of numbers in five values.
prices = [8, 9, 10, 11, 12, 12, 13, 14, 15, 16, 18, 45]
plt.boxplot([grades, prices])
plt.xticks([1, 2], ["Grades", "Prices"])
plt.title("Two box plots")
plt.show()
Change it and run: change the price 45 to 19. The circle disappears: 19 is not unusual.
How to read one box:
- The line inside the box is the median: half of the values are below it, half are above it.
- The box goes from the first quarter to the third quarter: the middle half of the values is inside the box.
- The two lines (the whiskers) go to the smallest and the largest value that are not unusual.
- A separate circle is an outlier: a value far away from the others. The price 45 is one.
- 1The smallest value that is not unusual.
- 2The first quarter: a quarter of the values are below it.
- 3The median: half below, half above.
- 4The third quarter: three quarters of the values are below it.
- 5The largest value that is not unusual.
- 6An outlier: a value far away from the others.
A box plot is the fastest way to compare the spread of several groups and to notice unusual values.
3.5Pie chart: shares of a whole
payment = ["Card", "Cash", "Bonus"]
orders = [180, 90, 30]
plt.pie(orders, labels=payment, autopct="%1.0f%%")
plt.title("How the orders were paid")
plt.show()
Change it and run: add a fourth group, "Gift card" with 5 orders. The thin slice is hard to read.
autopct="%1.0f%%" writes the percent into every slice. A pie chart is only good for very few groups (2 to 4) that make a whole. The eye compares angles badly: with five or more slices, or with slices of a similar size, use a bar chart instead.
Try it yourself
Show a hint
plt.show(), then start the second: plt.boxplot(minutes). The outlier is the separate circle.Show the solution
import matplotlib.pyplot as plt
minutes = [12, 15, 18, 20, 21, 22, 24, 25, 25, 27, 30, 41]
plt.hist(minutes, bins=4, edgecolor="white")
plt.title("Minutes needed for the test")
plt.xlabel("Minutes")
plt.ylabel("Students")
plt.show()
plt.boxplot(minutes)
plt.title("Minutes needed for the test")
plt.ylabel("Minutes")
plt.show()

4Several charts in one figure
4.1The figure and the axes
Until now every chart was alone. To put two or more charts next to each other, use plt.subplots. It gives two things:
- the figure: the whole picture,
- the axes: the single charts inside it. One chart is called an
Axes.
import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5]
visitors = [120, 135, 128, 160, 190]
sales = [15, 18, 14, 22, 30]
fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))
axes[0].plot(days, visitors, marker="o")
axes[0].set_title("Visitors")
axes[0].set_xlabel("Day")
axes[1].bar(days, sales, color="teal")
axes[1].set_title("Sales")
axes[1].set_xlabel("Day")
plt.tight_layout()
plt.show()
Change it and run: change plt.subplots(1, 2, ...) to plt.subplots(2, 1, ...) with figsize=(5, 6): the charts are now under each other.
plt.subplots(1, 2)makes 1 row and 2 columns of charts.axesis an array of the two charts:axes[0]is the left one,axes[1]the right one.- You draw on a chart with its own methods:
axes[0].plot(...),axes[1].bar(...). They are the same drawing functions as before. - The describing methods have
set_in the name:
| With plt. | On one chart |
|---|---|
plt.title("...") | ax.set_title("...") |
plt.xlabel("...") | ax.set_xlabel("...") |
plt.ylabel("...") | ax.set_ylabel("...") |
plt.xlim(0, 10), plt.ylim(0, 10) | ax.set_xlim(0, 10), ax.set_ylim(0, 10) |
plt.legend(), plt.grid(True) | ax.legend(), ax.grid(True) |
plt.tight_layout()moves the charts so that titles and labels do not overlap. Write it beforeplt.show().
4.2A grid of charts
With more than one row, axes is a table of charts: the first index is the row, the second is the column, as in a 2D NumPy array.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 60)
fig, axes = plt.subplots(2, 2, figsize=(8, 6))
axes[0, 0].plot(x, x)
axes[0, 0].set_title("y = x")
axes[0, 1].plot(x, x ** 2)
axes[0, 1].set_title("y = x squared")
axes[1, 0].plot(x, x ** 3)
axes[1, 0].set_title("y = x cubed")
axes[1, 1].plot(x, np.abs(x))
axes[1, 1].set_title("y = |x|")
fig.suptitle("Four simple functions")
plt.tight_layout()
plt.show()
Change it and run: draw np.sqrt(np.abs(x)) in the last chart.
fig.suptitle(...) writes one title above all the charts.
Try it yourself
Show a hint
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5)), then axes[0].bar(months, income) and axes[0].set_title("Income"). End with plt.tight_layout() and plt.show().Show the solution
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr"]
income = [40, 55, 48, 70]
costs = [30, 35, 33, 45]
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
axes[0].bar(months, income)
axes[0].set_title("Income")
axes[1].bar(months, costs)
axes[1].set_title("Costs")
plt.tight_layout()
plt.show()
5Charts from our data
A chart function needs lists of values. A column of a table is such a list, so plt.hist(df["price"]) works directly. But most charts need a summary first: a bar chart of the cities needs one number for every city, not 300 rows. The rule of this part:
First make the small table you want to show (with value_counts or groupby), look at it, then draw it.
5.1One number column: histogram
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
plt.hist(df["price"], bins=20, color="teal", edgecolor="white")
plt.title("Prices of the orders")
plt.xlabel("Price")
plt.ylabel("Orders")
plt.show()
Change it and run: change bins=20 to bins=8. The tail to the right is still there.
A histogram needs no summary: it counts by itself. Most orders cost less than 60, and a few expensive ones make a long tail to the right. The mean (50.64) is pulled to the right by this tail, so the median (35.96) describes a typical order better. You could not see this from the two numbers alone.
5.2Counting a text column: bar chart
counts = df["city"].value_counts()
print(counts)
plt.bar(counts.index, counts.values, color="teal")
plt.title("Orders by city")
plt.ylabel("Orders")
plt.show()Output
city Baku 128 Ganja 54 Sumqayit 48 Quba 30 Lankaran 22 Shaki 10 Name: count, dtype: int64

Change it and run: count the column category instead of city.
value_counts gives a Series: the cities are its labels (counts.index) and the numbers are its values (counts.values). These are exactly the names and the heights that plt.bar needs. The bars are already sorted, because value_counts sorts.
5.3A summary by group: bar chart
df["total"] = df["price"] * df["units"]
money = df.groupby("category")["total"].sum().sort_values()
print(money)
plt.barh(money.index, money.values, color="teal")
plt.title("Money by category")
plt.xlabel("Money")
plt.show()Output
category Home 2737.28 Sports 3297.39 Books 3629.74 Clothing 4846.81 Tech 7424.00 Name: total, dtype: float64

Change it and run: group by city instead of category.
Every groupby result of the last lesson can be drawn in this way: the labels on one axis, the values on the other. Sorted from small to large, barh puts the largest bar at the top.
5.4Change over time: line chart
df["month"] = pd.to_datetime(df["date"]).dt.month
monthly = df.groupby("month").size()
print(monthly.tolist())
plt.plot(monthly.index, monthly.values, marker="o", color="teal")
plt.title("Orders by month, 2025")
plt.xlabel("Month")
plt.ylabel("Orders")
plt.xticks(range(1, 13))
plt.grid(True)
plt.show()Output
[18, 16, 22, 20, 22, 24, 26, 24, 28, 26, 34, 40]

Change it and run: draw the units sold in every month: df.groupby("month")["units"].sum().
The months have an order, so a line is right. The chart shows at once what the list of twelve numbers hides: the orders grow during the year and jump in November and December. plt.xticks(range(1, 13)) writes every month number on the axis.
5.5Two number columns: scatter chart
Is a customer with more orders also a customer who brings more money? Make one row for every customer, then draw the two columns against each other.
per_customer = df.groupby("customer").agg(orders=("price", "size"), money=("total", "sum"))
print(per_customer.head())
plt.scatter(per_customer["orders"], per_customer["money"], color="teal")
plt.title("Customers: orders and money")
plt.xlabel("Number of orders")
plt.ylabel("Money spent")
plt.show()Output
orders money customer Aida 3 464.73 Anar 7 641.64 Ayan 3 306.33 Aylin 18 1194.38 Aysel 10 1214.83

Change it and run: add alpha=0.5 to plt.scatter.
Every point is one customer. The points go up from left to right: more orders mean more money. One customer is far above the others at the right: the shop's best customer.
When many points lie on top of each other, add alpha=0.5: the points become half transparent and the crowded places look darker.
5.6The spread of several groups: box plot
plt.boxplot needs a list of lists: the prices of every category.
categories = ["Books", "Clothing", "Home", "Sports", "Tech"]
prices = []
for name in categories:
prices.append(df[df["category"] == name]["price"])
plt.boxplot(prices)
plt.xticks(range(1, 6), categories)
plt.title("Prices by category")
plt.ylabel("Price")
plt.show()
Change it and run: draw the column rating instead of price.
Books, Home and Sports have low prices close to each other. Clothing is spread wider, and Tech has the widest range and several outliers: a few very expensive products. This took a loop to prepare. In Part 7 Seaborn draws the same chart in one line.
5.7The shortcut of pandas: .plot
A Series and a DataFrame have their own plot method. It calls Matplotlib for you and uses the labels of the Series for the axis.
counts = df["category"].value_counts()
counts.plot(kind="bar", color="teal")
plt.title("Orders by category")
plt.ylabel("Orders")
plt.show()
Change it and run: change kind="bar" to kind="barh", then to kind="pie".
kind chooses the chart: "line" (the default), "bar", "barh", "hist", "box", "pie". After it, every plt. function works as before, because the chart is a Matplotlib chart. It is a fast way to look at a summary. rot=0 inside plot writes the names horizontally.
Try it yourself
price with 10 bins, then a second one with 30 bins. Which one shows the shape better?Show a hint
plt.show() calls: plt.hist(df["price"], bins=10), title and labels, plt.show(), then the same with bins=30.Show the solution
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
plt.hist(df["price"], bins=10)
plt.title("Prices of the orders, 10 bins")
plt.xlabel("Price")
plt.ylabel("Orders")
plt.show()
plt.hist(df["price"], bins=30)
plt.title("Prices of the orders, 30 bins")
plt.xlabel("Price")
plt.ylabel("Orders")
plt.show()

6Seaborn: the first charts
6.1What Seaborn is
Seaborn is a library built on top of Matplotlib. It draws the same kinds of charts with less code, it has a few chart types that Matplotlib does not have, and it can take a whole table and the names of its columns. Everybody imports it with the short name sns:
import seaborn as snsA Seaborn chart is a Matplotlib chart. So plt.title, plt.xlabel, plt.figure(figsize=...), plt.savefig and plt.show work in the same way, and you always import both libraries. In Anaconda and in Google Colab Seaborn is already installed.
This part draws the charts of Part 3 again, from the same small lists, so that you can compare the two libraries. In Seaborn the values are always given with their names: x= and y=.
6.2Line chart: sns.lineplot
import matplotlib.pyplot as plt
import seaborn as sns
days = [1, 2, 3, 4, 5]
visitors = [120, 135, 128, 160, 190]
sns.lineplot(x=days, y=visitors, marker="o")
plt.title("Visitors of the shop")
plt.xlabel("Day")
plt.ylabel("Visitors")
plt.show()
Change it and run: add color="tomato" and linestyle="--".
It is the chart of plt.plot(days, visitors, marker="o"). The parameters color, linestyle, marker and linewidth have the same names and values as in Matplotlib.
6.3Bar chart: sns.barplot
cities = ["Baku", "Ganja", "Shaki", "Quba"]
orders = [128, 54, 10, 30]
sns.barplot(x=cities, y=orders, color="teal")
plt.title("Orders by city")
plt.ylabel("Orders")
plt.show()
Change it and run: swap the two names: x=orders, y=cities. The bars lie down.
For horizontal bars there is no second function: swap the two names, sns.barplot(x=orders, y=cities).
6.4Histogram: sns.histplot
grades = [55, 62, 64, 68, 70, 71, 73, 74, 75, 76, 78, 79, 80, 82, 83, 85, 88, 90, 94, 98]
sns.histplot(x=grades, bins=5, color="teal")
plt.title("Exam grades of 20 students")
plt.xlabel("Grade")
plt.ylabel("Students")
plt.show()
Change it and run: change bins=5 to bins=10.
The same five bars as plt.hist(grades, bins=5).
6.5Scatter chart: sns.scatterplot
hours = [1, 2, 2, 3, 4, 5, 5, 6, 7, 8]
grade = [52, 55, 61, 64, 70, 68, 77, 80, 85, 91]
sns.scatterplot(x=hours, y=grade, color="teal")
plt.title("Study hours and exam grade")
plt.xlabel("Hours of study")
plt.ylabel("Grade")
plt.show()
6.6Box plot: sns.boxplot
prices = [8, 9, 10, 11, 12, 12, 13, 14, 15, 16, 18, 45]
sns.boxplot(x=prices, color="teal")
plt.title("Prices of 12 products")
plt.xlabel("Price")
plt.show()
Change it and run: write y=prices instead of x=prices. The box stands up.
With x= the box lies down, with y= it stands. The outlier 45 is the separate point at the right.
6.7The two libraries side by side
| Chart | Matplotlib | Seaborn |
|---|---|---|
| Line | plt.plot(x, y) | sns.lineplot(x=x, y=y) |
| Bars | plt.bar(names, values) | sns.barplot(x=names, y=values) |
| Horizontal bars | plt.barh(names, values) | sns.barplot(x=values, y=names) |
| Histogram | plt.hist(values, bins=5) | sns.histplot(x=values, bins=5) |
| Scatter | plt.scatter(x, y) | sns.scatterplot(x=x, y=y) |
| Box plot | plt.boxplot(values) | sns.boxplot(x=values) |
| Pie | plt.pie(values, labels=names) | Seaborn has no pie chart |
With lists the two libraries need about the same code. The real strength of Seaborn is the next part: charts straight from a table.
6.8The look of Seaborn: sns.set_theme()
sns.set_theme()
days = [1, 2, 3, 4, 5]
visitors = [120, 135, 128, 160, 190]
sns.lineplot(x=days, y=visitors, marker="o")
plt.title("Visitors of the shop")
plt.xlabel("Day")
plt.ylabel("Visitors")
plt.show()
Change it and run: remove the line sns.set_theme() and run again.
sns.set_theme() changes the look of all charts that follow in the notebook, the Matplotlib ones too: a light gray background with a white grid, and softer colours. Write it once, after the imports. Without it the charts are drawn in the plain Matplotlib look, as the five charts above. sns.reset_defaults() brings the plain look back.
Try it yourself
Show a hint
x and the names are y: sns.barplot(x=sold, y=fruits).Show the solution
import matplotlib.pyplot as plt
import seaborn as sns
fruits = ["Apple", "Pear", "Plum", "Cherry"]
sold = [40, 25, 18, 32]
sns.barplot(x=sold, y=fruits, color="teal")
plt.title("Fruit sold")
plt.xlabel("Kilograms")
plt.show()
7Seaborn with a table
7.1data, x and y
The functions of the last part can take a table and the names of its columns, and then they do the summary themselves. Every one of them has the same shape:
sns.barplot(data=df, x="category", y="price")datais the table,xandyare the names of the columns for the two axes.
Seaborn also writes the axis labels from the column names.
7.2countplot: how many rows of every group
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
df = pd.read_csv("orders.csv")
sns.countplot(data=df, x="category")
plt.title("Orders by category")
plt.show()
Change it and run: change x="category" to x="city".
sns.countplot counted the rows of every category by itself. There was no value_counts and no list of heights: the names of the table and of the column were enough. Compare it with "Counting a text column" in Part 5.
7.3Horizontal bars in a chosen order
order = df["city"].value_counts().index
sns.countplot(data=df, y="city", order=order, color="teal")
plt.title("Orders by city")
plt.show()
Change it and run: remove order=order. The bars are no longer sorted.
y="city"instead ofx="city"draws horizontal bars.order=takes a list of the group names in the order you want.value_counts().indexis the list of cities from the most orders to the fewest.color=sets the colour of the bars. One colour is enough here: the bars already have names, so different colours would add nothing.
7.4barplot: a summary of every group
print(df.groupby("category")["price"].mean().round(2))
sns.barplot(data=df, x="category", y="price", errorbar=None, color="teal")
plt.title("Mean price by category")
plt.show()Output
category Books 25.44 Clothing 70.59 Home 26.79 Sports 38.99 Tech 90.08 Name: price, dtype: float64

Change it and run: change y="price" to y="units": the mean number of units of every category.
sns.barplot groups the rows by the x column and draws the mean of the y column for every group. It is the chart of df.groupby("category")["price"].mean(). Compare the bars with the printed numbers.
Without errorbar=None every bar gets a thin black line that shows how sure the mean is. It belongs to the statistics lessons of the next module; until then switch it off.
For another summary, name it with estimator:
df["total"] = df["price"] * df["units"]
sns.barplot(data=df, x="category", y="total", estimator="sum", errorbar=None, color="teal")
plt.title("Money by category")
plt.ylabel("Money")
plt.show()
Change it and run: change estimator="sum" to estimator="max".
estimator="sum" draws the sum of every group. Other values are "median", "max", "min".
7.5histplot: the spread of one column
sns.histplot(data=df, x="price", bins=20, kde=True, color="teal")
plt.title("Prices of the orders")
plt.show()
Change it and run: remove kde=True.
It is the histogram of Part 5. kde=True adds a smooth line over the bars that follows the shape of the spread. It makes the shape easier to see: one high hill at the low prices and a long tail to the right.
7.6boxplot: the spread of every group
sns.boxplot(data=df, x="category", y="price", color="teal")
plt.title("Prices by category")
plt.show()
Change it and run: change x="category" to x="city".
One line instead of the loop of Part 5. Seaborn made a box for every category and wrote the names on the axis.
7.7scatterplot: two number columns
per_customer = df.groupby("customer").agg(orders=("price", "size"), money=("total", "sum"))
sns.scatterplot(data=per_customer, x="orders", y="money", color="teal")
plt.title("Customers: orders and money")
plt.show()
Seaborn does not summarise here: a scatter chart draws every row of the table as a point. So the table must already have one row for every thing you want as a point: here one row for every customer.
7.8lineplot: change over time
df["month"] = pd.to_datetime(df["date"]).dt.month
sns.lineplot(data=df, x="month", y="total", estimator="sum", errorbar=None, marker="o", color="teal")
plt.title("Money by month, 2025")
plt.ylabel("Money")
plt.xticks(range(1, 13))
plt.show()
Change it and run: remove estimator="sum". The line now shows the mean money of an order in every month.
sns.lineplot groups the rows by the x column, as barplot does. With estimator="sum" every point is the money of one month. Without estimator it draws the mean of every month.
Try it yourself
sns.barplot. Give the chart a title.Show a hint
df.groupby("category")["price"].median(). The chart: sns.barplot(data=df, x="category", y="price", estimator="median", errorbar=None).Show the solution
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("orders.csv")
print(df.groupby("category")["price"].median())
sns.barplot(data=df, x="category", y="price", estimator="median", errorbar=None, color="teal")
plt.title("Median price by category")
plt.show()Output
category Books 25.905 Clothing 64.900 Home 24.960 Sports 35.000 Tech 59.900 Name: price, dtype: float64

8Seaborn continued: groups in colour, heatmaps and more
8.1hue: a third column as colour
Most Seaborn functions have the parameter hue. It takes the name of one more column and splits the chart by it, with a colour for every group and a legend.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
full = df.merge(customers, on="customer", how="left")
sns.countplot(data=full, x="category", hue="gender")
plt.title("Orders by category and gender")
plt.show()
Change it and run: change hue="gender" to hue="city".
Every category now has two bars next to each other, one for each gender. It is the chart of a groupby with two columns. In plain Matplotlib these grouped bars take many lines; here it is one parameter. This is the place where different colours are right: the colour now says something that the axis does not.
The gender is in the second file, so the two tables were joined first, as in the last lesson.
The data file: customers.csv
40 customers, 4 columns. A cell marked "empty" has no value in the file: pandas shows it as NaN.
Loading the table ...
hue works in the same way in a scatter chart:
sns.scatterplot(data=df, x="price", y="units", hue="category", alpha=0.7)
plt.title("Price and units of every order")
plt.show()
Change it and run: change hue="category" to hue="city". Does the city explain the price?
Every point is one order, and the colour is its category. Two things are visible. The expensive orders (at the right) are almost always one unit, and the orders with 4 or 5 units are cheap products: cheap things are bought in larger numbers. And the expensive points are Tech and Clothing.
A line for every group needs the same parameter. Here the money of every month, for two cities:
df["total"] = df["price"] * df["units"]
df["month"] = pd.to_datetime(df["date"]).dt.month
two = df[df["city"].isin(["Baku", "Ganja"])]
sns.lineplot(data=two, x="month", y="total", hue="city", estimator="sum", errorbar=None, marker="o")
plt.title("Money by month in two cities")
plt.ylabel("Money")
plt.xticks(range(1, 13))
plt.show()
Change it and run: use the cities "Sumqayit" and "Quba".
In Matplotlib this chart takes two summaries and two plt.plot calls with labels. Seaborn splits the rows by city, draws a line for each and makes the legend.
And two histograms in one chart:
two = df[df["category"].isin(["Books", "Clothing"])]
sns.histplot(data=two, x="price", hue="category", bins=20)
plt.title("Prices of Books and Clothing")
plt.show()
Change it and run: compare "Home" and "Tech".
The books are cheap and close together; the prices of Clothing are spread over a much wider range.
8.2violinplot: a box plot that shows the shape
sns.violinplot(data=df, x="category", y="price", color="teal")
plt.title("Prices by category")
plt.show()
Change it and run: change sns.violinplot to sns.boxplot and compare the two charts.
A violin plot answers the same question as a box plot, and it also shows where the values are: the violin is wide where many values are and thin where few are. The small box inside is the box plot. The shape is smoothed, so it can reach a little below the smallest value. Tech has a long thin neck: a few very expensive products far above the others. Use the box plot when you need the exact median and quarters, the violin when the shape matters.
8.3heatmap: a table as colours
A heatmap draws a table of numbers as a grid of coloured cells: the larger the number, the darker the cell. It is the chart of a pivot table.
table = pd.pivot_table(df, index="city", columns="category", values="price", aggfunc="count", fill_value=0)
print(table)
sns.heatmap(table, annot=True, fmt="d", cmap="Blues")
plt.title("Orders by city and category")
plt.show()Output
category Books Clothing Home Sports Tech city Baku 29 28 21 25 25 Ganja 17 10 7 10 10 Lankaran 9 2 7 3 1 Quba 5 4 9 2 10 Shaki 3 2 0 2 3 Sumqayit 11 5 9 5 18

Change it and run: change cmap="Blues" to cmap="Greens", and remove annot=True.
sns.heatmaptakes the table itself, notdata,xandy: the table is already the summary.annot=Truewrites the number into every cell, andfmt="d"writes it as a whole number.cmap="Blues"is the colour scale: light for small numbers, dark for large ones.fill_value=0inpivot_tablewrites 0 where a city has no orders of a category. Without it the cell would be a missing value.
The dark cells are found at once: Baku buys the most in every category, and Sumqayit buys a lot of Tech.
8.4A heatmap of correlations
The correlation of two number columns is a number from -1 to 1. Close to 1: when one grows, the other grows too. Close to -1: when one grows, the other falls. Close to 0: they have nothing to do with each other. You will learn it properly in the statistics lessons; here it is enough to read it. df.corr() calculates it for every pair of columns, and a heatmap shows the result.
corr = df[["price", "units", "rating"]].corr().round(2)
print(corr)
sns.heatmap(corr, annot=True, cmap="coolwarm", vmin=-1, vmax=1)
plt.title("Correlations")
plt.show()Output
price units rating price 1.00 -0.32 0.05 units -0.32 1.00 -0.07 rating 0.05 -0.07 1.00

Change it and run: remove vmin=-1, vmax=1. The colours change, the numbers do not.
vmin=-1, vmax=1 fixes the colour scale, so that 0 is in the middle (a pale colour), positive values are red and negative values are blue. Price and units have -0.32: the more expensive the product, the fewer units in the order, as the scatter chart above showed. The rating has almost nothing to do with the price. Every column has 1 with itself.
This chart is used in almost every machine learning project to see which columns are related.
8.5regplot: a scatter chart with a trend line
per_customer = df.groupby("customer").agg(orders=("price", "size"), money=("total", "sum"))
sns.regplot(data=per_customer, x="orders", y="money", ci=None, color="teal")
plt.title("Customers: orders and money")
plt.show()
Change it and run: remove ci=None. A shaded band appears around the line.
sns.regplot draws the points and the straight line that fits them best. The line shows the direction of the cloud. ci=None switches off the shaded band around the line. How this line is calculated is the subject of the Linear Regression lesson.
8.6pairplot: every pair of number columns at once
sns.pairplot(df[["price", "units", "rating"]], height=2)
plt.show()
Change it and run: leave out "rating": only two columns.
sns.pairplot takes a table and draws a grid: a scatter chart for every pair of number columns, and a histogram of each column on the diagonal. It is a first look at a new table in one line. Give it only a few columns: with ten columns it draws a hundred small charts.
pairplot makes its own figure, so plt.figure(figsize=...) does not change its size. Use its parameter height (the size of one small chart).
8.7Seaborn inside plt.subplots
Seaborn functions that draw one chart have the parameter ax: the chart of a figure to draw on. So Seaborn charts can sit next to each other.
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
sns.histplot(data=df, x="price", bins=20, color="teal", ax=axes[0])
axes[0].set_title("Prices of the orders")
sns.countplot(data=df, x="rating", color="teal", ax=axes[1])
axes[1].set_title("Ratings")
plt.tight_layout()
plt.show()
Change it and run: draw the column units in the second chart.
The ratings are missing in 36 orders. Seaborn leaves these rows out, so the bars show the 264 orders that have a rating.
Try it yourself
Show a hint
sns.countplot(data=df, x="units", hue="category"). Which categories are bought in larger numbers?Show the solution
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("orders.csv")
sns.countplot(data=df, x="units", hue="category")
plt.title("Units in an order, by category")
plt.show()
9Choosing the right chart
Start from the question, not from the chart.
| The question | The columns | The chart | Matplotlib | Seaborn |
|---|---|---|---|---|
| How does it change over time? | time and a number | line | plt.plot | sns.lineplot |
| How many rows has every group? | one text column | bar | value_counts, then plt.bar | sns.countplot |
| How do the groups compare in a number? | a text and a number column | bar | groupby, then plt.bar | sns.barplot |
| Where are most of the values? | one number column | histogram | plt.hist | sns.histplot |
| How wide is the spread, are there outliers? | a number column (and a text column) | box plot | plt.boxplot | sns.boxplot, sns.violinplot |
| Do two numbers move together? | two number columns | scatter | plt.scatter | sns.scatterplot, sns.regplot |
| What share of the whole? | 2 to 4 groups | pie | plt.pie | (use Matplotlib) |
| Two groupings at once? | two text columns | grouped bars or heatmap | hue=, sns.heatmap | |
| Which number columns are related? | several number columns | heatmap of corr() | sns.heatmap, sns.pairplot |
Choose the question. The question chooses the chart.
Line chart
The x axis has an order (days, months, years), so the points are joined.
- Matplotlib
- plt.plot(months, values)
- Seaborn
- sns.lineplot(data=df, x="month", y="total")
9.1Matplotlib or Seaborn?
- Seaborn when the data is a table and the chart is one of its types: less code, the summary and the labels are done for you, and
huegives groups in colour. - Matplotlib for lists and arrays, for the curve of a formula, and for everything around the chart: the size, the title, the limits, the ticks, several charts in one figure, saving.
In practice you use both in the same cell: Seaborn draws, Matplotlib finishes.
9.2A checklist for every chart
- One question for one chart. Say the question before you draw.
- A title and axis labels, with the unit where there is one.
- Sorted bars, unless the groups have their own order (months, ratings).
- Colour only where it means something.
- Honest axes: bars start at 0.
- Look at the numbers behind the chart at least once (
printthe summary).
9.3From a question to a chart
Question: in which months does the shop earn the most, and is it the same for every category?
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
df["month"] = pd.to_datetime(df["date"]).dt.month
table = pd.pivot_table(df, index="category", columns="month", values="total", aggfunc="sum", fill_value=0)
print(table.round(0).astype(int))
plt.figure(figsize=(10, 3.5))
sns.heatmap(table, cmap="Blues")
plt.title("Money by category and month, 2025")
plt.show()Output
month 1 2 3 4 5 6 7 8 9 10 11 12 category Books 275 225 237 302 133 136 356 461 557 271 307 370 Clothing 459 338 65 436 232 178 504 259 247 992 412 724 Home 200 81 207 133 50 122 208 193 26 196 763 558 Sports 49 111 370 140 540 290 414 238 467 165 126 388 Tech 135 330 595 375 815 1542 270 788 300 495 309 1471

Change it and run: add annot=True, fmt=".0f" to sns.heatmap.
The steps were the same as always: prepare the columns (total, month), make the summary (a pivot table), look at it, draw it, describe it. The printed table has 60 numbers and is hard to read. In the heatmap the dark cells stand out, and they answer the question: Tech in June and in December earns far more than anything else, but the other categories have their best months elsewhere, Clothing in October and Home in November.
Try it yourself
Show a hint
rating = df.groupby("city")["rating"].mean().round(2).sort_values(), then plt.barh(rating.index, rating.values). A rating goes from 1 to 5: plt.xlim(0, 5) shows the whole scale.Show the solution
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
rating = df.groupby("city")["rating"].mean().round(2).sort_values()
print(rating)
plt.barh(rating.index, rating.values, color="teal")
plt.title("Mean rating by city")
plt.xlabel("Mean rating")
plt.xlim(0, 5)
plt.show()Output
city Shaki 3.50 Sumqayit 4.00 Baku 4.03 Lankaran 4.11 Ganja 4.12 Quba 4.31 Name: rating, dtype: float64

10Common mistakes
The red text is the real message Python shows. Where there is no message, the program runs but the chart is wrong: look at the two pictures.
import matplotlib as plt
Wrong
import matplotlib as plt plt.plot([3, 5, 4, 8])
AttributeError: module 'matplotlib' has no attribute 'plot'
Right
import matplotlib.pyplot as plt plt.plot([3, 5, 4, 8]) plt.show()

AttributeError. The drawing functions are in matplotlib.pyplot, not in matplotlib itself. Write import matplotlib.pyplot as plt.
x and y of different lengths
Wrong
import matplotlib.pyplot as plt days = [1, 2, 3, 4, 5] visitors = [120, 135, 128, 160] plt.plot(days, visitors)
ValueError: x and y must have same first dimension, but have shapes (5,) and (4,)
Right
import matplotlib.pyplot as plt days = [1, 2, 3, 4, 5] visitors = [120, 135, 128, 160, 190] plt.plot(days, visitors) plt.show()

ValueError. Every x needs its y. Count the values: there are 5 days and 4 numbers of visitors.
A wrong column name in Seaborn
Wrong
import pandas as pd
import seaborn as sns
df = pd.read_csv("orders.csv")
sns.barplot(data=df, x="Category", y="price")ValueError: Could not interpret value `Category` for `x`. An entry with this name does not appear in `data`.
Right
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("orders.csv")
sns.barplot(data=df, x="category", y="price", errorbar=None)
plt.show()
ValueError. The names are case-sensitive, as in pandas. The column is called category. Check the names with df.columns.
Two charts drawn into one
Wrong
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
plt.hist(df["price"], bins=20)
plt.title("Prices")
plt.hist(df["rating"], bins=5)
plt.title("Ratings")
plt.show()
Right
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
plt.hist(df["price"], bins=20)
plt.title("Prices")
plt.show()
plt.hist(df["rating"], bins=5)
plt.title("Ratings")
plt.show()

Without plt.show() (or plt.figure()) between them, the second chart is drawn on top of the first. The prices and the ratings share one chart and one title, and the ratings are a thin bar at the left. Finish the first chart with plt.show() before you start the second, and you get two charts.
A bar chart of rows that are not summarised
Wrong
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
plt.bar(df["category"], df["price"])
plt.title("Price by category?")
plt.show()
Right
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
mean_price = df.groupby("category")["price"].mean()
plt.bar(mean_price.index, mean_price.values)
plt.title("Mean price by category")
plt.show()
plt.bar draws one bar for every value it gets. There is no error, but the chart is wrong: 300 bars are drawn on top of each other in five places, and you see only the highest price of every category. Summarise first.
A line chart for groups without an order
Wrong
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
counts = df["city"].value_counts()
plt.plot(counts.index, counts.values)
plt.title("Orders by city")
plt.show()
Right
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
counts = df["city"].value_counts()
plt.bar(counts.index, counts.values)
plt.title("Orders by city")
plt.show()
The line says that something goes down from Baku to Shaki, but cities are not steps on a road. Use plt.bar for groups, and a line only for time or another real order.
A pie chart with many slices
Wrong
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
counts = df["product"].value_counts()
plt.pie(counts.values, labels=counts.index)
plt.title("Orders by product")
plt.show()
Right
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
counts = df["product"].value_counts().sort_values()
plt.figure(figsize=(6, 6))
plt.barh(counts.index, counts.values)
plt.title("Orders by product")
plt.show()
Nobody can compare these slices. A sorted plt.barh of the same numbers is read in a second.
plt.legend() without labels
Wrong
import matplotlib.pyplot as plt days = [1, 2, 3, 4, 5] plt.plot(days, [120, 135, 128, 160, 190]) plt.plot(days, [80, 95, 90, 110, 105]) plt.legend() plt.show()

Right
import matplotlib.pyplot as plt days = [1, 2, 3, 4, 5] plt.plot(days, [120, 135, 128, 160, 190], label="Baku") plt.plot(days, [80, 95, 90, 110, 105], label="Ganja") plt.legend() plt.show()

The legend has nothing to show. Give every line a label.
More mistakes in short:
| Mistake | What happens | Fix |
|---|---|---|
No plt.show() at the end | in some programs nothing is shown, in a notebook a line of text appears above the chart | end every chart with plt.show() |
plt.savefig after plt.show() | an empty picture is saved | save first, then show |
plt.figure(figsize=...) after the drawing | a second, empty chart appears | write it before the drawing |
plt.legend() without label= | an empty legend and a warning | give every line a label |
| No title and no axis labels | the reader has to guess | plt.title, plt.xlabel, plt.ylabel |
| A histogram for a text column, a bar chart for 300 different numbers | a chart that says nothing | histogram for one number column, bars for groups |
sns.barplot without estimator when you want sums | the bars show means | estimator="sum" |
Bars that do not start at 0 (plt.ylim(100, 130)) | small differences look huge | let bars start at 0 |
11Solved problems (easy to medium-hard)
Each problem has the task, the code, the chart and a short explanation. Where the chart shows a summary, the code prints the summary too.
11.1Level 1: Easy
Problem 1: The temperatures of a week
Draw the temperatures of seven days as a line with markers. Add a title and axis labels.
import matplotlib.pyplot as plt
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
temps = [18, 21, 19, 24, 26, 23, 20]
plt.plot(days, temps, marker="o", color="tomato")
plt.title("Temperature of the week")
plt.xlabel("Day")
plt.ylabel("Degrees")
plt.show()
Change it and run: add an eighth day, Mon with 17 degrees. What happens to the axis?
Why: The x values can be text: Matplotlib puts the names on the axis in the order of the list. The days have an order, so a line is right.
Problem 2: The grades of five students
Draw the grades as bars, sorted from the highest to the lowest.
import pandas as pd
import matplotlib.pyplot as plt
grades = pd.Series({"Aylin": 85, "Murad": 72, "Leyla": 91, "Kamran": 64, "Nigar": 78})
grades = grades.sort_values(ascending=False)
print(grades)
plt.bar(grades.index, grades.values, color="teal")
plt.title("Exam grades")
plt.ylabel("Grade")
plt.show()Output
Leyla 91 Aylin 85 Nigar 78 Murad 72 Kamran 64 dtype: int64

Change it and run: sort from the lowest to the highest grade.
Why: A Series keeps the names and the values together, so sorting it sorts both. Then the labels and the values go to plt.bar.
Problem 3: Two curves and a legend
Draw y = x and y = x squared for x from 0 to 3 in one chart, with a legend.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 3, 40)
plt.plot(x, x, label="y = x")
plt.plot(x, x ** 2, label="y = x squared", linestyle="--")
plt.title("Two functions")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.grid(True)
plt.show()
Change it and run: add a third curve, x ** 3, with a dotted line.
Why: Two plt.plot calls, one chart. The grid shows where the curves cross: at x = 1 both are 1.
Problem 4: How many units are in an order?
Draw how many orders have 1, 2, 3, 4 and 5 units.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
counts = df["units"].value_counts().sort_index()
print(counts)
plt.bar(counts.index, counts.values, color="teal")
plt.title("Units in an order")
plt.xlabel("Units")
plt.ylabel("Orders")
plt.show()Output
units 1 169 2 71 3 37 4 17 5 6 Name: count, dtype: int64

Change it and run: remove .sort_index(). The bars keep their places, because the x values are numbers.
Why: units is a number column, but it has only five different values, so each value is a group and bars are right. sort_index puts the bars in the order 1 to 5, not in the order of the counts: these groups have their own order.
Problem 5: The ratings
Draw how many orders got each rating, with Seaborn.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
df = pd.read_csv("orders.csv")
print(df["rating"].value_counts().sort_index())
sns.countplot(data=df, x="rating", color="teal")
plt.title("Ratings of the orders")
plt.show()Output
rating 1.0 12 2.0 18 3.0 34 4.0 77 5.0 123 Name: count, dtype: int64

Change it and run: add hue="category".
Why: Most customers give 4 or 5. The 36 orders without a rating are not in the chart. The labels are 1.0 to 5.0 because a number column with missing values is stored as decimals.
11.2Level 2: Medium
Problem 6: The five best customers
Draw the money of the five customers who spent the most, as horizontal bars with the best at the top.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
best = df.groupby("customer")["total"].sum().sort_values().tail(5)
print(best)
plt.barh(best.index, best.values, color="teal")
plt.title("The five best customers")
plt.xlabel("Money spent")
plt.show()Output
customer Aylin 1194.38 Aysel 1214.83 Konul 1348.08 Murad 1568.87 Ramin 2538.11 Name: total, dtype: float64

Change it and run: show the ten best customers.
Why: Sorted from small to large, the last five rows are the five largest, and barh draws the last one at the top.
Problem 7: Orders and money by month
Draw the money of every month as a line. Mark the best month in the title.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
df["month"] = pd.to_datetime(df["date"]).dt.month
money = df.groupby("month")["total"].sum()
best = money.idxmax()
print(money.round(2).tolist())
print(best)
plt.plot(money.index, money.values, marker="o", color="teal")
plt.title(f"Money by month (the best month: {best})")
plt.xlabel("Month")
plt.ylabel("Money")
plt.xticks(range(1, 13))
plt.grid(True)
plt.show()Output
[1118.03, 1085.53, 1473.77, 1384.73, 1770.02, 2268.12, 1752.02, 1938.49, 1596.42, 2119.2, 1917.28, 3511.61] 12

Change it and run: draw the number of orders instead of the money.
Why: A title is text, so an f-string can put a calculated value into it.
Problem 8: The prices of two categories
Compare how the prices of Books and Tech are spread: two histograms in one chart.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
books = df[df["category"] == "Books"]["price"]
tech = df[df["category"] == "Tech"]["price"]
print(round(books.median(), 2), round(tech.median(), 2))
plt.hist(books, bins=15, alpha=0.6, label="Books")
plt.hist(tech, bins=15, alpha=0.6, label="Tech")
plt.title("Prices of Books and Tech")
plt.xlabel("Price")
plt.ylabel("Orders")
plt.legend()
plt.show()Output
25.9 59.9

Change it and run: compare "Home" and "Clothing".
Why: alpha=0.6 makes the bars half transparent, so both histograms stay visible where they overlap. The books are all between 11 and 40; Tech starts about where the books end and goes up to 249.
Problem 9: The mean rating of every category
Draw the mean rating of every category with Seaborn. The scale of a rating is 1 to 5: show the whole scale.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
df = pd.read_csv("orders.csv")
print(df.groupby("category")["rating"].mean().round(2))
sns.barplot(data=df, x="category", y="rating", errorbar=None, color="teal")
plt.title("Mean rating by category")
plt.ylim(0, 5)
plt.show()Output
category Books 4.15 Clothing 4.17 Home 3.96 Sports 4.05 Tech 3.98 Name: rating, dtype: float64

Change it and run: change plt.ylim(0, 5) to plt.ylim(3.9, 4.2). The same numbers now look very different.
Why: The bars are almost equal: the categories are rated nearly the same, about 4. With plt.ylim(3.9, 4.2) the same numbers would look like a big difference. Bars start at 0.
Problem 10: Which city pays the most for an order?
Compare the prices of the cities with box plots, the cities in the order of their median price.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
df = pd.read_csv("orders.csv")
medians = df.groupby("city")["price"].median().sort_values(ascending=False)
print(medians.round(2))
sns.boxplot(data=df, x="city", y="price", order=medians.index, color="teal")
plt.title("Prices by city")
plt.show()Output
city Sumqayit 45.00 Shaki 37.45 Baku 35.96 Quba 35.96 Ganja 35.46 Lankaran 28.91 Name: price, dtype: float64

Change it and run: draw the column rating instead of price.
Why: order= takes the city names sorted by their median. Sumqayit has the highest median (45) and Lankaran the lowest (about 29), but the boxes of all cities overlap a lot: the city says little about the price. The 8 orders without a city are not drawn.
11.3Level 3: Medium-Hard
Problem 11: Two charts side by side
Show the number of orders and the money of every category next to each other, with the same order of the categories.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
summary = df.groupby("category").agg(orders=("price", "size"), money=("total", "sum")).sort_values("money")
print(summary)
fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))
axes[0].barh(summary.index, summary["orders"], color="gray")
axes[0].set_title("Orders")
axes[1].barh(summary.index, summary["money"], color="teal")
axes[1].set_title("Money")
fig.suptitle("Categories: orders and money")
plt.tight_layout()
plt.show()Output
orders money category Home 56 2737.28 Sports 48 3297.39 Books 74 3629.74 Clothing 54 4846.81 Tech 68 7424.00

Change it and run: sort the table by "orders" instead of "money".
Why: One summary table feeds both charts, so the categories are in the same order. Books have the most orders but only the third place in money; Tech has fewer orders and earns the most. One chart alone would not show this.
Problem 12: Cheap products are bought in larger numbers
Show the mean price of the orders with 1, 2, 3, 4 and 5 units.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
df = pd.read_csv("orders.csv")
print(df.groupby("units")["price"].mean().round(1))
sns.barplot(data=df, x="units", y="price", errorbar=None, color="teal")
plt.title("Mean price by the number of units")
plt.ylabel("Mean price")
plt.show()Output
units 1 62.8 2 42.6 3 28.6 4 21.5 5 21.0 Name: price, dtype: float64

Change it and run: use estimator="median".
Why: The bars fall from left to right: the more units in an order, the cheaper the product. It is the same fact as the correlation of -0.32 in Part 8, shown in a way that everybody can read.
Problem 13: Money by category and gender
Join the orders with the customers and draw the money of every category, split by gender.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
df["total"] = df["price"] * df["units"]
full = df.merge(customers, on="customer", how="left")
print(full.groupby(["category", "gender"])["total"].sum().round(0))
sns.barplot(data=full, x="category", y="total", hue="gender", estimator="sum", errorbar=None)
plt.title("Money by category and gender")
plt.ylabel("Money")
plt.show()Output
category gender
Books F 1663.0
M 1967.0
Clothing F 1740.0
M 2952.0
Home F 1299.0
M 1382.0
Sports F 1529.0
M 1769.0
Tech F 3683.0
M 3741.0
Name: total, dtype: float64
Change it and run: change hue="gender" to hue="city".
Why: hue="gender" makes two bars for every category. The three orders of customers who are not in customers.csv have no gender and are left out.
Problem 14: Do older customers spend more?
Make one row for every customer with the age and the money spent, and draw them against each other with a trend line.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")
df["total"] = df["price"] * df["units"]
money = df.groupby("customer")["total"].sum().reset_index()
table = customers.merge(money, on="customer")
print(table.shape)
print(table[["age", "total"]].corr().round(2))
sns.regplot(data=table, x="age", y="total", ci=None, color="teal")
plt.title("Age and money spent")
plt.ylabel("Money spent")
plt.show()Output
(38, 5)
age total
age 1.00 0.12
total 0.12 1.00
Change it and run: add ci=None again after removing it, and compare.
Why: The inner join keeps the customers who are in both tables. Look at the correlation and at the line together: a line that is almost flat and a cloud without direction mean that the age says little about the money.
Problem 15: Four charts about the shop
Make one figure with four charts: the prices (histogram), the money by category (bars), the orders by month (line) and the ratings (bars).
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme()
df = pd.read_csv("orders.csv")
df["total"] = df["price"] * df["units"]
df["month"] = pd.to_datetime(df["date"]).dt.month
monthly = df.groupby("month").size()
order = df.groupby("category")["total"].sum().sort_values(ascending=False).index
fig, axes = plt.subplots(2, 2, figsize=(11, 7))
sns.histplot(data=df, x="price", bins=20, color="teal", ax=axes[0, 0])
axes[0, 0].set_title("Prices")
sns.barplot(data=df, x="category", y="total", estimator="sum", errorbar=None, order=order, color="teal", ax=axes[0, 1])
axes[0, 1].set_title("Money by category")
axes[0, 1].set_ylabel("Money")
axes[1, 0].plot(monthly.index, monthly.values, marker="o", color="teal")
axes[1, 0].set_title("Orders by month")
axes[1, 0].set_xticks(range(1, 13))
sns.countplot(data=df, x="rating", color="teal", ax=axes[1, 1])
axes[1, 1].set_title("Ratings")
fig.suptitle("The shop in 2025")
plt.tight_layout()
plt.show()
Change it and run: put the box plot sns.boxplot(data=df, x="category", y="price", ax=axes[1, 1]) into the last chart.
Why: Seaborn charts get their place with ax=, the Matplotlib line is drawn with the method of its own chart, and every chart gets its title with set_title. Four questions, four charts, one picture.
12Practice problems (try them yourself)
Fifteen problems in three levels. They work like one notebook: the setup cell below imports the libraries and reads both files, and every problem is a cell that continues from it. So np, pd, plt, sns, df and customers are already there.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")Every chart needs a title and axis labels. Every problem asks for two things: print the numbers behind the chart, then draw the chart. Press Run: the printed numbers are compared with the expected ones, and the expected chart appears under your own so that you can compare the two. A problem that says it continues from another problem uses your own answer to that problem: it is run first, so the earlier answer must be right for the later one to be right. This is how a real notebook works.
Easy
A curve from an array, and the first two charts of the orders.
- 1.Make 50 values of
xfrom -2 to 2 andy = x ** 3. Print the first and the last value ofyon one line, then draw the curve. Give the chart a title and axis labels.Show a hint
x = np.linspace(-2, 2, 50). The first value isy[0], the last isy[-1]:print(y[0], y[-1]). Thenplt.plot(x, y).Show one possible solution
Python, continues from the cells abovex = np.linspace(-2, 2, 50) y = x ** 3 print(y[0], y[-1]) plt.plot(x, y) plt.title("y = x cubed") plt.xlabel("x") plt.ylabel("y") plt.show()Output
-8.0 8.0

- 2.Print the number of orders of every category (
value_counts), then draw these numbers as a bar chart with Matplotlib. Give the chart a title and axis labels.Show a hint
Store the result:counts = df["category"].value_counts(). The names arecounts.index, the heights arecounts.values.Show one possible solution
Python, continues from the cells abovecounts = df["category"].value_counts() print(counts) plt.bar(counts.index, counts.values) plt.title("Orders by category") plt.ylabel("Orders") plt.show()Output
category Books 74 Tech 68 Home 56 Clothing 54 Sports 48 Name: count, dtype: int64

- 3.Print the number of orders of every city (
value_counts), then draw it withsns.countplot, the city with the most orders first. Give the chart a title.Show a hint
sns.countplot(data=df, x="city", order=...). The order is the list of cities fromvalue_counts: its.index.Show one possible solution
Python, continues from the cells abovecounts = df["city"].value_counts() print(counts) sns.countplot(data=df, x="city", order=counts.index) plt.title("Orders by city") plt.show()Output
city Baku 128 Ganja 54 Sumqayit 48 Quba 30 Lankaran 22 Shaki 10 Name: count, dtype: int64

Medium
A summary first, then the chart: lines, bars, box plots and a scatter chart.
- 4.Add a column
month(the month number ofdate). Print the units sold in every month as a list, then draw them as a line chart with markers and with all twelve months on the axis. Give the chart a title and axis labels.Show a hint
df["month"] = pd.to_datetime(df["date"]).dt.month, thendf.groupby("month")["units"].sum(). Print it with.tolist().plt.xticks(range(1, 13))writes every month.Show one possible solution
Python, continues from the cells abovedf["month"] = pd.to_datetime(df["date"]).dt.month units = df.groupby("month")["units"].sum() print(units.tolist()) plt.plot(units.index, units.values, marker="o") plt.title("Units sold by month") plt.xlabel("Month") plt.ylabel("Units") plt.xticks(range(1, 13)) plt.show()Output
[34, 29, 40, 33, 34, 42, 48, 40, 48, 40, 61, 71]

- 5.Print the mean price of every city, rounded to 2 decimals and sorted from the smallest to the largest. Then draw it as horizontal bars, so that the largest is at the top. Give the chart a title and axis labels.
Show a hint
df.groupby("city")["price"].mean().round(2).sort_values().plt.barhdraws the last value at the top.Show one possible solution
Python, continues from the cells abovemean_price = df.groupby("city")["price"].mean().round(2).sort_values() print(mean_price) plt.barh(mean_price.index, mean_price.values) plt.title("Mean price by city") plt.xlabel("Mean price") plt.show()Output
city Lankaran 34.94 Baku 48.84 Quba 49.91 Ganja 54.11 Shaki 56.50 Sumqayit 58.64 Name: price, dtype: float64

- 6.Print the median rating of every category. Then draw the ratings of the categories as box plots with Seaborn. Give the chart a title.
Show a hint
df.groupby("category")["rating"].median()for the numbers,sns.boxplot(data=df, x="category", y="rating")for the chart.Show one possible solution
Python, continues from the cells aboveprint(df.groupby("category")["rating"].median()) sns.boxplot(data=df, x="category", y="rating") plt.title("Ratings by category") plt.show()Output
category Books 4.0 Clothing 4.5 Home 4.0 Sports 4.0 Tech 4.0 Name: rating, dtype: float64

- 7.Add a column
total(price times units). Print the money of every city, rounded to 2 decimals, the largest first. Then draw it withsns.barplotandestimator="sum", the bars in the same order. Give the chart a title.Show a hint
The summary:df.groupby("city")["total"].sum().round(2).sort_values(ascending=False). Its.indexis the list fororder=. Adderrorbar=None.Show one possible solution
Python, continues from the cells abovedf["total"] = df["price"] * df["units"] money = df.groupby("city")["total"].sum().round(2).sort_values(ascending=False) print(money) sns.barplot(data=df, x="city", y="total", estimator="sum", errorbar=None, order=money.index) plt.title("Money by city") plt.ylabel("Money") plt.show()Output
city Baku 9093.10 Ganja 4213.20 Sumqayit 4201.60 Quba 1986.82 Lankaran 1358.15 Shaki 649.64 Name: total, dtype: float64

- 8.Do expensive products get better ratings? Print the correlations of the columns
priceandrating, rounded to 2 decimals (df[["price", "rating"]].corr()). Then draw a scatter chart of the two columns for all orders, withalpha=0.5. Give the chart a title and axis labels.Show a hint
plt.scatter(df["price"], df["rating"], alpha=0.5). A number close to 0 and a cloud without direction mean: no.Show one possible solution
Python, continues from the cells aboveprint(df[["price", "rating"]].corr().round(2)) plt.scatter(df["price"], df["rating"], alpha=0.5) plt.title("Price and rating") plt.xlabel("Price") plt.ylabel("Rating") plt.show()Output
price rating price 1.00 0.05 rating 0.05 1.00

- 9.This problem continues from Problem 4: the table already has the column
monthfrom your answer there. Print the number of orders of Baku in every month as a list, then the same for Ganja. Then draw both as lines with markers in one chart, with a legend and all twelve months on the axis. Give the chart a title and axis labels.Show a hint
The rows of one city, then the groups:df[df["city"] == "Baku"].groupby("month").size(). Twoplt.plotcalls withlabel=, thenplt.legend().Show one possible solution
Python, continues from the cells abovebaku = df[df["city"] == "Baku"].groupby("month").size() ganja = df[df["city"] == "Ganja"].groupby("month").size() print(baku.tolist()) print(ganja.tolist()) plt.plot(baku.index, baku.values, marker="o", label="Baku") plt.plot(ganja.index, ganja.values, marker="o", label="Ganja") plt.title("Orders by month") plt.xlabel("Month") plt.ylabel("Orders") plt.xticks(range(1, 13)) plt.legend() plt.show()Output
[10, 9, 12, 6, 8, 9, 15, 7, 14, 14, 5, 19] [3, 2, 3, 10, 2, 4, 4, 6, 3, 6, 5, 6]

Medium-Hard
Several charts in one figure, a heatmap, charts of two joined tables, and problems that build on each other.
- 10.Print the highest price of Clothing and the highest price of Home on one line. Then make a figure with two charts next to each other: a histogram of the prices of Clothing and a histogram of the prices of Home, each with 10 bins, a title, and the same limits of the x axis: from 0 to 140.
Show a hint
fig, axes = plt.subplots(1, 2, figsize=(10, 3.5)). On one chart:axes[0].hist(...),axes[0].set_title(...),axes[0].set_xlim(0, 140). End withplt.tight_layout().Show one possible solution
Python, continues from the cells aboveclothing = df[df["category"] == "Clothing"]["price"] home = df[df["category"] == "Home"]["price"] print(clothing.max(), home.max()) fig, axes = plt.subplots(1, 2, figsize=(10, 3.5)) axes[0].hist(clothing, bins=10) axes[0].set_title("Prices of Clothing") axes[0].set_xlim(0, 140) axes[1].hist(home, bins=10) axes[1].set_title("Prices of Home") axes[1].set_xlim(0, 140) plt.tight_layout() plt.show()Output
129.0 49.9

- 11.Make a table of the mean rating with the cities in the rows and the categories in the columns, rounded to 1 decimal. Print it, then draw it as a heatmap with the numbers in the cells. Give the chart a title.
Show a hint
pd.pivot_table(df, index="city", columns="category", values="rating", aggfunc="mean").round(1), thensns.heatmap(table, annot=True, cmap="Blues"). Shaki has no order in Home: this cell stays empty.Show one possible solution
Python, continues from the cells abovetable = pd.pivot_table(df, index="city", columns="category", values="rating", aggfunc="mean").round(1) print(table) sns.heatmap(table, annot=True, cmap="Blues") plt.title("Mean rating by city and category") plt.show()Output
category Books Clothing Home Sports Tech city Baku 4.0 4.1 3.8 4.0 4.1 Ganja 4.2 4.3 3.3 4.1 4.2 Lankaran 4.1 3.5 4.0 4.3 5.0 Quba 4.2 5.0 4.1 4.5 4.2 Shaki 4.3 3.0 NaN 4.0 2.5 Sumqayit 4.2 4.6 4.4 3.5 3.6

- 12.Join the orders with the customers and store the result in
full(the default join is right here: an order without a customer has no gender). Print the number of orders by city and gender (groupbywith two columns andsize). Then draw the number of orders of every city, split by gender. Give the chart a title.Show a hint
full = df.merge(customers, on="customer"), thenfull.groupby(["city", "gender"]).size(). The chart:sns.countplot(data=full, x="city", hue="gender").Show one possible solution
Python, continues from the cells abovefull = df.merge(customers, on="customer") print(full.groupby(["city", "gender"]).size()) sns.countplot(data=full, x="city", hue="gender") plt.title("Orders by city and gender") plt.show()Output
city gender Baku F 69 M 56 Ganja F 22 M 32 Lankaran F 5 M 17 Quba F 22 M 8 Shaki F 5 M 5 Sumqayit F 5 M 43 dtype: int64
- 13.This problem continues from Problem 12: the joined table
fullis already there. Add a columntotal(price times units) tofull. Print the money of the customers who joined in each year (joined), rounded to 2 decimals. Then draw it as bars with the years on the axis. Give the chart a title and axis labels.Show a hint
money = full.groupby("joined")["total"].sum().round(2).plt.bar(money.index, money.values), andplt.xticks(money.index)writes only the real years.Show one possible solution
Python, continues from the cells abovefull["total"] = full["price"] * full["units"] money = full.groupby("joined")["total"].sum().round(2) print(money) plt.bar(money.index, money.values) plt.title("Money by the year the customer joined") plt.xlabel("Year") plt.ylabel("Money") plt.xticks(money.index) plt.show()Output
joined 2021 3596.13 2022 1347.42 2023 5154.50 2024 6362.77 2025 5263.75 Name: total, dtype: float64

- 14.Make a table
per_productwith one row for every product: its mean price in the columnpriceand the units sold in the columnunits. Print the correlations of this table, rounded to 2 decimals. Then draw the two columns as a scatter chart, the price on the x axis. Give the chart a title and axis labels.Show a hint
df.groupby("product").agg(price=("price", "mean"), units=("units", "sum")), thenper_product.corr().round(2). A negative number means: the higher the price, the fewer units.Show one possible solution
Python, continues from the cells aboveper_product = df.groupby("product").agg(price=("price", "mean"), units=("units", "sum")) print(per_product.corr().round(2)) plt.scatter(per_product["price"], per_product["units"]) plt.title("Products: price and units sold") plt.xlabel("Mean price") plt.ylabel("Units sold") plt.show()Output
price units price 1.00 -0.59 units -0.59 1.00

- 15.Make one figure with four charts about the customers of
customers.csvand their orders. Choose the four questions yourself and write each question as the title of its chart.Show a hint
fig, axes = plt.subplots(2, 2, figsize=(11, 7)). A Seaborn chart gets its place withax=axes[0, 0]. For the money of every customer: group the orders bycustomer, thencustomers.merge(...).Show one possible solution
Python, continues from the cells abovedf["total"] = df["price"] * df["units"] spent = df.groupby("customer")["total"].sum().reset_index() people = customers.merge(spent, on="customer", how="left") fig, axes = plt.subplots(2, 2, figsize=(11, 7)) sns.histplot(data=people, x="age", bins=8, ax=axes[0, 0]) axes[0, 0].set_title("How old are the customers?") sns.countplot(data=people, x="gender", ax=axes[0, 1]) axes[0, 1].set_title("How many women and men?") sns.countplot(data=people, x="joined", ax=axes[1, 0]) axes[1, 0].set_title("In which year did they join?") sns.scatterplot(data=people, x="age", y="total", ax=axes[1, 1]) axes[1, 1].set_title("Do older customers spend more?") plt.tight_layout() plt.show()
13Check yourself
Twelve quick questions. Your answers are saved in this browser, so you can leave the page and continue later. Each finished round is kept as an attempt below the questions; you can delete the attempts at any time.
0 of 12 answered.
14Quick summary
| Task | Code |
|---|---|
| Import | import matplotlib.pyplot as plt, import seaborn as sns |
| A line | plt.plot(x, y, color="teal", linestyle="--", marker="o") |
| Describe the chart | plt.title("..."), plt.xlabel("..."), plt.ylabel("...") |
| Several lines | one plt.plot(..., label="...") for each, then plt.legend() |
| Size, grid | plt.figure(figsize=(8, 3)) before the drawing, plt.grid(True) |
| Limits, ticks | plt.ylim(0, 200), plt.xticks(positions, names) |
| Save, show | plt.savefig("name.png"), then plt.show() |
| Bars | plt.bar(names, values), plt.barh(names, values) |
| Histogram | plt.hist(values, bins=20) |
| Scatter | plt.scatter(x, y, alpha=0.5) |
| Box plot | plt.boxplot([list1, list2]) |
| Pie | plt.pie(values, labels=names, autopct="%1.0f%%") |
| Several charts | fig, axes = plt.subplots(1, 2), axes[0].plot(...), axes[0].set_title(...), plt.tight_layout() |
| A summary as a chart | s = df["city"].value_counts(), then plt.bar(s.index, s.values) |
| The pandas shortcut | s.plot(kind="bar") |
| Seaborn from lists | sns.lineplot(x=days, y=visitors), sns.barplot(x=names, y=values) |
| The Seaborn look | sns.set_theme() |
| Rows of every group | sns.countplot(data=df, x="city") |
| A summary of every group | sns.barplot(data=df, x="category", y="price", estimator="sum", errorbar=None) |
| Spread of one column | sns.histplot(data=df, x="price", bins=20, kde=True) |
| Spread of every group | sns.boxplot(data=df, x="category", y="price"), sns.violinplot(...) |
| Two number columns | sns.scatterplot(data=df, x="price", y="units"), sns.regplot(...) |
| Change over time | sns.lineplot(data=df, x="month", y="total", estimator="sum", errorbar=None) |
| Groups in colour | hue="gender" |
| A table as colours | sns.heatmap(table, annot=True, cmap="Blues") |
| All pairs of columns | sns.pairplot(df[["price", "units", "rating"]]) |
| A Seaborn chart in a figure | sns.histplot(..., ax=axes[0]) |