{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 12: Data visualization: Matplotlib and Seaborn basics\n",
    "\n",
    "Asiman Data School, Module 1: Foundations of Python Programming. Week 6, Thursday.\n",
    "\n",
    "This notebook follows the lesson page. Read the text, run the cell under it with Shift + Enter, then change the values in the cell and run it again. Seeing the output change is how the rules become clear.\n",
    "\n",
    "Run the cells from top to bottom. A cell that draws a chart shows it under the cell when you run it. The practice problems are in a separate notebook, topic-12-practice.ipynb.\n",
    "\n",
    "Inside a part the cells continue from each other: a cell uses the variables of the cells above it. To start in the middle, run the part from its first cell.\n",
    "\n",
    "This notebook reads the files orders.csv and customers.csv. Put them into the same folder as the notebook. On the Asiman Data School website they are already there.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. The first chart\n",
    "2. Making a chart readable\n",
    "3. The main chart types\n",
    "4. Several charts in one figure\n",
    "5. Charts from our data\n",
    "6. Seaborn: the first charts\n",
    "7. Seaborn with a table\n",
    "8. Seaborn continued: groups in colour, heatmaps and more\n",
    "9. Choosing the right chart\n",
    "10. Common mistakes\n",
    "11. Solved problems (easy to medium-hard)\n",
    "12. Practice problems (try them yourself) (in topic-12-practice.ipynb)\n",
    "13. Check yourself (on the website)\n",
    "14. Quick summary"
   ],
   "id": "t12-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: seeing data\n",
    "\n",
    "What matters most in this lesson. Three things matter most today. First, the order of every chart: draw, describe (`plt.title`, `plt.xlabel`, `plt.ylabel`), `plt.show()`. Second, the five chart types and the question each one answers: a line for change over time, bars for groups, a histogram for one number column, a scatter chart for two number columns, a box plot for spread and outliers. Third, the rule for real data: summarise first with `value_counts` or `groupby`, then draw.\n",
    "\n",
    "Seaborn draws the same charts with less code when the data is a table; learn `data`, `x`, `y` and `hue`. Heatmaps, `regplot`, `pairplot` and the violin plot are a first look: you will use them again in the statistics and machine learning lessons. There are 15 solved problems. Start with Level 1 and come back to the others when you repeat the topic.\n",
    "\n",
    "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.\n",
    "\n",
    "You should already know the last lessons: NumPy arrays, reading a file with pandas, choosing columns, `groupby`, `value_counts` and `merge`.\n",
    "\n",
    "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.\n",
    "\n",
    "## 1. The first chart\n",
    "\n",
    "### 1.1 What Matplotlib is\n",
    "\n",
    "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`:\n",
    "\n",
    "```python\n",
    "import matplotlib.pyplot as plt\n",
    "```\n",
    "\n",
    "In Anaconda and in Google Colab it is already installed.\n",
    "\n",
    "### 1.2 A line through four numbers\n",
    "\n",
    "Change it and run: add a fifth number to the list. The line gets one more point."
   ],
   "id": "t12-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "plt.plot([3, 5, 4, 8])\n",
    "plt.show()"
   ],
   "id": "t12-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Two lines of code make a chart:\n",
    "\n",
    "- `plt.plot(...)` draws the values as points and joins them with a line.\n",
    "- `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.\n",
    "\n",
    "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.\n",
    "\n",
    "### 1.3 x and y\n",
    "\n",
    "Usually you give both: first the x values, then the y values.\n",
    "\n",
    "Change it and run: change the last number of `visitors` to 100. The line turns down."
   ],
   "id": "t12-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "days = [1, 2, 3, 4, 5]\n",
    "visitors = [120, 135, 128, 160, 190]\n",
    "\n",
    "plt.plot(days, visitors)\n",
    "plt.show()"
   ],
   "id": "t12-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 1.4 A title and axis labels\n",
    "\n",
    "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.\n",
    "\n",
    "Change it and run: change the title to `\"Visitors in the first week\"`."
   ],
   "id": "t12-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(days, visitors)\n",
    "plt.title(\"Visitors of the shop\")\n",
    "plt.xlabel(\"Day\")\n",
    "plt.ylabel(\"Visitors\")\n",
    "plt.show()"
   ],
   "id": "t12-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The order is always the same: draw, describe, show. Every `plt.` line between the drawing and `plt.show()` adds something to the same chart.\n",
    "\n",
    "### 1.5 A chart from NumPy arrays\n",
    "\n",
    "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.\n",
    "\n",
    "Change it and run: change 50 to 5 in `np.linspace`. Now you see the corners of the curve."
   ],
   "id": "t12-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "x = np.linspace(0, 5, 50)\n",
    "y = x ** 2\n",
    "\n",
    "print(x[:4])\n",
    "print(y[:4])\n",
    "\n",
    "plt.plot(x, y)\n",
    "plt.title(\"y = x squared\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"y\")\n",
    "plt.show()"
   ],
   "id": "t12-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "## 2. Making a chart readable\n",
    "\n",
    "### 2.1 Colour, line style and marker\n",
    "\n",
    "`plt.plot` has parameters for the look of the line.\n",
    "\n",
    "Change it and run: use `color=\"tomato\"`, `linestyle=\":\"` and `marker=\"s\"`."
   ],
   "id": "t12-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "days = [1, 2, 3, 4, 5]\n",
    "visitors = [120, 135, 128, 160, 190]\n",
    "\n",
    "plt.plot(days, visitors, color=\"teal\", linestyle=\"--\", marker=\"o\", linewidth=2)\n",
    "plt.title(\"Visitors of the shop\")\n",
    "plt.xlabel(\"Day\")\n",
    "plt.ylabel(\"Visitors\")\n",
    "plt.show()"
   ],
   "id": "t12-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Parameter | What it changes | Common values |\n",
    "| --- | --- | --- |\n",
    "| `color` | the colour | `\"teal\"`, `\"tomato\"`, `\"gray\"`, `\"black\"`, `\"orange\"`, `\"green\"` |\n",
    "| `linestyle` | the kind of line | `\"-\"` solid, `\"--\"` dashed, `\":\"` dotted |\n",
    "| `marker` | the sign at every point | `\"o\"` circle, `\"s\"` square, `\"^\"` triangle |\n",
    "| `linewidth` | the thickness | a number, for example `2` |\n",
    "\n",
    "A marker is useful when there are few points: the reader sees where the real values are.\n",
    "\n",
    "### 2.2 Several lines and a legend\n",
    "\n",
    "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.\n",
    "\n",
    "Change it and run: remove `plt.legend()`. Which line is which shop?"
   ],
   "id": "t12-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "baku = [120, 135, 128, 160, 190]\n",
    "ganja = [80, 95, 90, 110, 105]\n",
    "\n",
    "plt.plot(days, baku, marker=\"o\", label=\"Baku\")\n",
    "plt.plot(days, ganja, marker=\"o\", label=\"Ganja\")\n",
    "plt.title(\"Visitors of two shops\")\n",
    "plt.xlabel(\"Day\")\n",
    "plt.ylabel(\"Visitors\")\n",
    "plt.legend()\n",
    "plt.show()"
   ],
   "id": "t12-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Matplotlib chooses a different colour for every line. Without `plt.legend()` the labels are not shown.\n",
    "\n",
    "### 2.3 A grid and the size of the chart\n",
    "\n",
    "Change it and run: change `figsize` to `(4, 4)`, then to `(10, 2)`."
   ],
   "id": "t12-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(8, 3))\n",
    "plt.plot(days, visitors, marker=\"o\")\n",
    "plt.title(\"Visitors of the shop\")\n",
    "plt.xlabel(\"Day\")\n",
    "plt.ylabel(\"Visitors\")\n",
    "plt.grid(True)\n",
    "plt.show()"
   ],
   "id": "t12-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `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.\n",
    "- `plt.grid(True)` draws light lines, so values are easier to read.\n",
    "\n",
    "### 2.4 The limits and the ticks of the axes\n",
    "\n",
    "Matplotlib chooses the limits of the axes from the data. You can set them yourself.\n",
    "\n",
    "Change it and run: change `plt.ylim(0, 200)` to `plt.ylim(100, 200)`. The same numbers look like a faster growth."
   ],
   "id": "t12-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(days, visitors, marker=\"o\")\n",
    "plt.title(\"Visitors of the shop\")\n",
    "plt.xlabel(\"Day\")\n",
    "plt.ylabel(\"Visitors\")\n",
    "plt.ylim(0, 200)\n",
    "plt.xticks(days, [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\"])\n",
    "plt.show()"
   ],
   "id": "t12-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `plt.ylim(0, 200)` makes the vertical axis go from 0 to 200 (`plt.xlim` does 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.\n",
    "- `plt.xticks(positions, names)` says where the marks of the axis are and what is written there.\n",
    "\n",
    "### 2.5 Saving a chart as a picture"
   ],
   "id": "t12-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(days, visitors, marker=\"o\")\n",
    "plt.title(\"Visitors of the shop\")\n",
    "plt.savefig(\"visitors.png\")\n",
    "plt.show()"
   ],
   "id": "t12-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "## 3. The main chart types\n",
    "\n",
    "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.\n",
    "\n",
    "| Chart | The question it answers |\n",
    "| --- | --- |\n",
    "| Line | How does a value change over time (or along an order)? |\n",
    "| Bar | How do a few groups compare? |\n",
    "| Histogram | How are the values of one column spread: where are most of them? |\n",
    "| Scatter | Do two number columns move together? |\n",
    "| Box plot | Where is the middle, how wide is the spread, are there unusual values? |\n",
    "| Pie | What share of the whole does each group have (only for 2 to 4 groups)? |\n",
    "\n",
    "You already know the line chart. Use it when the x axis has an order: days, months, years, steps.\n",
    "\n",
    "### 3.1 Bar chart: comparing groups\n",
    "\n",
    "Change it and run: add a fifth city, Sumqayit with 48 orders, to both lists."
   ],
   "id": "t12-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "cities = [\"Baku\", \"Ganja\", \"Shaki\", \"Quba\"]\n",
    "orders = [128, 54, 10, 30]\n",
    "\n",
    "plt.bar(cities, orders, color=\"teal\")\n",
    "plt.title(\"Orders by city\")\n",
    "plt.ylabel(\"Orders\")\n",
    "plt.show()"
   ],
   "id": "t12-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "When the names are long or there are many groups, turn the bars: `plt.barh` draws horizontal bars.\n",
    "\n",
    "Change it and run: change the order of the two lists so that Baku is at the bottom."
   ],
   "id": "t12-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cities = [\"Shaki\", \"Quba\", \"Ganja\", \"Baku\"]\n",
    "orders = [10, 30, 54, 128]\n",
    "\n",
    "plt.barh(cities, orders, color=\"teal\")\n",
    "plt.title(\"Orders by city\")\n",
    "plt.xlabel(\"Orders\")\n",
    "plt.show()"
   ],
   "id": "t12-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`barh` draws the first group at the bottom. Sorted bars are much easier to read than bars in a random order.\n",
    "\n",
    "### 3.2 Histogram: how the values are spread\n",
    "\n",
    "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.\n",
    "\n",
    "Change it and run: change `bins=5` to `bins=10`, then to `bins=2`."
   ],
   "id": "t12-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = [55, 62, 64, 68, 70, 71, 73, 74, 75, 76, 78, 79, 80, 82, 83, 85, 88, 90, 94, 98]\n",
    "\n",
    "plt.hist(grades, bins=5, color=\"teal\", edgecolor=\"white\")\n",
    "plt.title(\"Exam grades of 20 students\")\n",
    "plt.xlabel(\"Grade\")\n",
    "plt.ylabel(\"Students\")\n",
    "plt.show()"
   ],
   "id": "t12-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "A histogram looks like a bar chart, but it is a different thing:\n",
    "\n",
    "|  | Bar chart | Histogram |\n",
    "| --- | --- | --- |\n",
    "| What is on the x axis | groups (names) | intervals of numbers |\n",
    "| What you give | names and one value for each | one long list of numbers |\n",
    "| The question | How do groups compare? | Where are most of the values? |\n",
    "\n",
    "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.\n",
    "\n",
    "### 3.3 Scatter chart: two number columns together\n",
    "\n",
    "A scatter chart draws one point for every pair of values. It shows whether two things move together.\n",
    "\n",
    "Change it and run: add a student who studied 8 hours and got 50. One point is now far from the others."
   ],
   "id": "t12-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hours = [1, 2, 2, 3, 4, 5, 5, 6, 7, 8]\n",
    "grade = [52, 55, 61, 64, 70, 68, 77, 80, 85, 91]\n",
    "\n",
    "plt.scatter(hours, grade, color=\"teal\")\n",
    "plt.title(\"Study hours and exam grade\")\n",
    "plt.xlabel(\"Hours of study\")\n",
    "plt.ylabel(\"Grade\")\n",
    "plt.show()"
   ],
   "id": "t12-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "The points are not joined with a line, because they have no order: each point is a separate student.\n",
    "\n",
    "### 3.4 Box plot: middle, spread and unusual values\n",
    "\n",
    "A box plot shows a list of numbers in five values.\n",
    "\n",
    "Change it and run: change the price 45 to 19. The circle disappears: 19 is not unusual."
   ],
   "id": "t12-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = [8, 9, 10, 11, 12, 12, 13, 14, 15, 16, 18, 45]\n",
    "\n",
    "plt.boxplot([grades, prices])\n",
    "plt.xticks([1, 2], [\"Grades\", \"Prices\"])\n",
    "plt.title(\"Two box plots\")\n",
    "plt.show()"
   ],
   "id": "t12-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How to read one box:\n",
    "\n",
    "- The line inside the box is the median: half of the values are below it, half are above it.\n",
    "- The box goes from the first quarter to the third quarter: the middle half of the values is inside the box.\n",
    "- The two lines (the whiskers) go to the smallest and the largest value that are not unusual.\n",
    "- A separate circle is an outlier: a value far away from the others. The price 45 is one.\n",
    "\n",
    "A box plot is the fastest way to compare the spread of several groups and to notice unusual values.\n",
    "\n",
    "### 3.5 Pie chart: shares of a whole\n",
    "\n",
    "Change it and run: add a fourth group, `\"Gift card\"` with 5 orders. The thin slice is hard to read."
   ],
   "id": "t12-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "payment = [\"Card\", \"Cash\", \"Bonus\"]\n",
    "orders = [180, 90, 30]\n",
    "\n",
    "plt.pie(orders, labels=payment, autopct=\"%1.0f%%\")\n",
    "plt.title(\"How the orders were paid\")\n",
    "plt.show()"
   ],
   "id": "t12-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "## 4. Several charts in one figure\n",
    "\n",
    "### 4.1 The figure and the axes\n",
    "\n",
    "Until now every chart was alone. To put two or more charts next to each other, use `plt.subplots`. It gives two things:\n",
    "\n",
    "- the figure: the whole picture,\n",
    "- the axes: the single charts inside it. One chart is called an `Axes`.\n",
    "\n",
    "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."
   ],
   "id": "t12-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "days = [1, 2, 3, 4, 5]\n",
    "visitors = [120, 135, 128, 160, 190]\n",
    "sales = [15, 18, 14, 22, 30]\n",
    "\n",
    "fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))\n",
    "\n",
    "axes[0].plot(days, visitors, marker=\"o\")\n",
    "axes[0].set_title(\"Visitors\")\n",
    "axes[0].set_xlabel(\"Day\")\n",
    "\n",
    "axes[1].bar(days, sales, color=\"teal\")\n",
    "axes[1].set_title(\"Sales\")\n",
    "axes[1].set_xlabel(\"Day\")\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ],
   "id": "t12-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `plt.subplots(1, 2)` makes 1 row and 2 columns of charts. `axes` is an array of the two charts: `axes[0]` is the left one, `axes[1]` the right one.\n",
    "- You draw on a chart with its own methods: `axes[0].plot(...)`, `axes[1].bar(...)`. They are the same drawing functions as before.\n",
    "- The describing methods have `set_` in the name:\n",
    "\n",
    "| With `plt.` | On one chart |\n",
    "| --- | --- |\n",
    "| `plt.title(\"...\")` | `ax.set_title(\"...\")` |\n",
    "| `plt.xlabel(\"...\")` | `ax.set_xlabel(\"...\")` |\n",
    "| `plt.ylabel(\"...\")` | `ax.set_ylabel(\"...\")` |\n",
    "| `plt.xlim(0, 10)`, `plt.ylim(0, 10)` | `ax.set_xlim(0, 10)`, `ax.set_ylim(0, 10)` |\n",
    "| `plt.legend()`, `plt.grid(True)` | `ax.legend()`, `ax.grid(True)` |\n",
    "\n",
    "- `plt.tight_layout()` moves the charts so that titles and labels do not overlap. Write it before `plt.show()`.\n",
    "\n",
    "### 4.2 A grid of charts\n",
    "\n",
    "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.\n",
    "\n",
    "Change it and run: draw `np.sqrt(np.abs(x))` in the last chart."
   ],
   "id": "t12-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "x = np.linspace(-3, 3, 60)\n",
    "\n",
    "fig, axes = plt.subplots(2, 2, figsize=(8, 6))\n",
    "\n",
    "axes[0, 0].plot(x, x)\n",
    "axes[0, 0].set_title(\"y = x\")\n",
    "\n",
    "axes[0, 1].plot(x, x ** 2)\n",
    "axes[0, 1].set_title(\"y = x squared\")\n",
    "\n",
    "axes[1, 0].plot(x, x ** 3)\n",
    "axes[1, 0].set_title(\"y = x cubed\")\n",
    "\n",
    "axes[1, 1].plot(x, np.abs(x))\n",
    "axes[1, 1].set_title(\"y = |x|\")\n",
    "\n",
    "fig.suptitle(\"Four simple functions\")\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ],
   "id": "t12-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`fig.suptitle(...)` writes one title above all the charts.\n",
    "\n",
    "## 5. Charts from our data\n",
    "\n",
    "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:\n",
    "\n",
    "First make the small table you want to show (with `value_counts` or `groupby`), look at it, then draw it.\n",
    "\n",
    "### 5.1 One number column: histogram\n",
    "\n",
    "Change it and run: change `bins=20` to `bins=8`. The tail to the right is still there."
   ],
   "id": "t12-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "\n",
    "plt.hist(df[\"price\"], bins=20, color=\"teal\", edgecolor=\"white\")\n",
    "plt.title(\"Prices of the orders\")\n",
    "plt.xlabel(\"Price\")\n",
    "plt.ylabel(\"Orders\")\n",
    "plt.show()"
   ],
   "id": "t12-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 5.2 Counting a text column: bar chart\n",
    "\n",
    "Change it and run: count the column `category` instead of `city`."
   ],
   "id": "t12-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "counts = df[\"city\"].value_counts()\n",
    "print(counts)\n",
    "\n",
    "plt.bar(counts.index, counts.values, color=\"teal\")\n",
    "plt.title(\"Orders by city\")\n",
    "plt.ylabel(\"Orders\")\n",
    "plt.show()"
   ],
   "id": "t12-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "### 5.3 A summary by group: bar chart\n",
    "\n",
    "Change it and run: group by `city` instead of `category`."
   ],
   "id": "t12-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "money = df.groupby(\"category\")[\"total\"].sum().sort_values()\n",
    "print(money)\n",
    "\n",
    "plt.barh(money.index, money.values, color=\"teal\")\n",
    "plt.title(\"Money by category\")\n",
    "plt.xlabel(\"Money\")\n",
    "plt.show()"
   ],
   "id": "t12-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 5.4 Change over time: line chart\n",
    "\n",
    "Change it and run: draw the units sold in every month: `df.groupby(\"month\")[\"units\"].sum()`."
   ],
   "id": "t12-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"month\"] = pd.to_datetime(df[\"date\"]).dt.month\n",
    "monthly = df.groupby(\"month\").size()\n",
    "print(monthly.tolist())\n",
    "\n",
    "plt.plot(monthly.index, monthly.values, marker=\"o\", color=\"teal\")\n",
    "plt.title(\"Orders by month, 2025\")\n",
    "plt.xlabel(\"Month\")\n",
    "plt.ylabel(\"Orders\")\n",
    "plt.xticks(range(1, 13))\n",
    "plt.grid(True)\n",
    "plt.show()"
   ],
   "id": "t12-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 5.5 Two number columns: scatter chart\n",
    "\n",
    "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.\n",
    "\n",
    "Change it and run: add `alpha=0.5` to `plt.scatter`."
   ],
   "id": "t12-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "per_customer = df.groupby(\"customer\").agg(orders=(\"price\", \"size\"), money=(\"total\", \"sum\"))\n",
    "print(per_customer.head())\n",
    "\n",
    "plt.scatter(per_customer[\"orders\"], per_customer[\"money\"], color=\"teal\")\n",
    "plt.title(\"Customers: orders and money\")\n",
    "plt.xlabel(\"Number of orders\")\n",
    "plt.ylabel(\"Money spent\")\n",
    "plt.show()"
   ],
   "id": "t12-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "When many points lie on top of each other, add `alpha=0.5`: the points become half transparent and the crowded places look darker.\n",
    "\n",
    "### 5.6 The spread of several groups: box plot\n",
    "\n",
    "`plt.boxplot` needs a list of lists: the prices of every category.\n",
    "\n",
    "Change it and run: draw the column `rating` instead of `price`."
   ],
   "id": "t12-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "categories = [\"Books\", \"Clothing\", \"Home\", \"Sports\", \"Tech\"]\n",
    "prices = []\n",
    "for name in categories:\n",
    "    prices.append(df[df[\"category\"] == name][\"price\"])\n",
    "\n",
    "plt.boxplot(prices)\n",
    "plt.xticks(range(1, 6), categories)\n",
    "plt.title(\"Prices by category\")\n",
    "plt.ylabel(\"Price\")\n",
    "plt.show()"
   ],
   "id": "t12-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 5.7 The shortcut of pandas: `.plot`\n",
    "\n",
    "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.\n",
    "\n",
    "Change it and run: change `kind=\"bar\"` to `kind=\"barh\"`, then to `kind=\"pie\"`."
   ],
   "id": "t12-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "counts = df[\"category\"].value_counts()\n",
    "\n",
    "counts.plot(kind=\"bar\", color=\"teal\")\n",
    "plt.title(\"Orders by category\")\n",
    "plt.ylabel(\"Orders\")\n",
    "plt.show()"
   ],
   "id": "t12-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "## 6. Seaborn: the first charts\n",
    "\n",
    "### 6.1 What Seaborn is\n",
    "\n",
    "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`:\n",
    "\n",
    "```python\n",
    "import seaborn as sns\n",
    "```\n",
    "\n",
    "A 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.\n",
    "\n",
    "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=`.\n",
    "\n",
    "### 6.2 Line chart: `sns.lineplot`\n",
    "\n",
    "Change it and run: add `color=\"tomato\"` and `linestyle=\"--\"`."
   ],
   "id": "t12-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "days = [1, 2, 3, 4, 5]\n",
    "visitors = [120, 135, 128, 160, 190]\n",
    "\n",
    "sns.lineplot(x=days, y=visitors, marker=\"o\")\n",
    "plt.title(\"Visitors of the shop\")\n",
    "plt.xlabel(\"Day\")\n",
    "plt.ylabel(\"Visitors\")\n",
    "plt.show()"
   ],
   "id": "t12-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 6.3 Bar chart: `sns.barplot`\n",
    "\n",
    "Change it and run: swap the two names: `x=orders, y=cities`. The bars lie down."
   ],
   "id": "t12-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cities = [\"Baku\", \"Ganja\", \"Shaki\", \"Quba\"]\n",
    "orders = [128, 54, 10, 30]\n",
    "\n",
    "sns.barplot(x=cities, y=orders, color=\"teal\")\n",
    "plt.title(\"Orders by city\")\n",
    "plt.ylabel(\"Orders\")\n",
    "plt.show()"
   ],
   "id": "t12-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For horizontal bars there is no second function: swap the two names, `sns.barplot(x=orders, y=cities)`.\n",
    "\n",
    "### 6.4 Histogram: `sns.histplot`\n",
    "\n",
    "Change it and run: change `bins=5` to `bins=10`."
   ],
   "id": "t12-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = [55, 62, 64, 68, 70, 71, 73, 74, 75, 76, 78, 79, 80, 82, 83, 85, 88, 90, 94, 98]\n",
    "\n",
    "sns.histplot(x=grades, bins=5, color=\"teal\")\n",
    "plt.title(\"Exam grades of 20 students\")\n",
    "plt.xlabel(\"Grade\")\n",
    "plt.ylabel(\"Students\")\n",
    "plt.show()"
   ],
   "id": "t12-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same five bars as `plt.hist(grades, bins=5)`.\n",
    "\n",
    "### 6.5 Scatter chart: `sns.scatterplot`"
   ],
   "id": "t12-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hours = [1, 2, 2, 3, 4, 5, 5, 6, 7, 8]\n",
    "grade = [52, 55, 61, 64, 70, 68, 77, 80, 85, 91]\n",
    "\n",
    "sns.scatterplot(x=hours, y=grade, color=\"teal\")\n",
    "plt.title(\"Study hours and exam grade\")\n",
    "plt.xlabel(\"Hours of study\")\n",
    "plt.ylabel(\"Grade\")\n",
    "plt.show()"
   ],
   "id": "t12-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.6 Box plot: `sns.boxplot`\n",
    "\n",
    "Change it and run: write `y=prices` instead of `x=prices`. The box stands up."
   ],
   "id": "t12-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = [8, 9, 10, 11, 12, 12, 13, 14, 15, 16, 18, 45]\n",
    "\n",
    "sns.boxplot(x=prices, color=\"teal\")\n",
    "plt.title(\"Prices of 12 products\")\n",
    "plt.xlabel(\"Price\")\n",
    "plt.show()"
   ],
   "id": "t12-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `x=` the box lies down, with `y=` it stands. The outlier 45 is the separate point at the right.\n",
    "\n",
    "### 6.7 The two libraries side by side\n",
    "\n",
    "| Chart | Matplotlib | Seaborn |\n",
    "| --- | --- | --- |\n",
    "| Line | `plt.plot(x, y)` | `sns.lineplot(x=x, y=y)` |\n",
    "| Bars | `plt.bar(names, values)` | `sns.barplot(x=names, y=values)` |\n",
    "| Horizontal bars | `plt.barh(names, values)` | `sns.barplot(x=values, y=names)` |\n",
    "| Histogram | `plt.hist(values, bins=5)` | `sns.histplot(x=values, bins=5)` |\n",
    "| Scatter | `plt.scatter(x, y)` | `sns.scatterplot(x=x, y=y)` |\n",
    "| Box plot | `plt.boxplot(values)` | `sns.boxplot(x=values)` |\n",
    "| Pie | `plt.pie(values, labels=names)` | Seaborn has no pie chart |\n",
    "\n",
    "With lists the two libraries need about the same code. The real strength of Seaborn is the next part: charts straight from a table.\n",
    "\n",
    "### 6.8 The look of Seaborn: `sns.set_theme()`\n",
    "\n",
    "Change it and run: remove the line `sns.set_theme()` and run again."
   ],
   "id": "t12-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.set_theme()\n",
    "\n",
    "days = [1, 2, 3, 4, 5]\n",
    "visitors = [120, 135, 128, 160, 190]\n",
    "\n",
    "sns.lineplot(x=days, y=visitors, marker=\"o\")\n",
    "plt.title(\"Visitors of the shop\")\n",
    "plt.xlabel(\"Day\")\n",
    "plt.ylabel(\"Visitors\")\n",
    "plt.show()"
   ],
   "id": "t12-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "## 7. Seaborn with a table\n",
    "\n",
    "### 7.1 `data`, `x` and `y`\n",
    "\n",
    "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:\n",
    "\n",
    "```python\n",
    "sns.barplot(data=df, x=\"category\", y=\"price\")\n",
    "```\n",
    "\n",
    "- `data` is the table,\n",
    "- `x` and `y` are the names of the columns for the two axes.\n",
    "\n",
    "Seaborn also writes the axis labels from the column names.\n",
    "\n",
    "### 7.2 `countplot`: how many rows of every group\n",
    "\n",
    "Change it and run: change `x=\"category\"` to `x=\"city\"`."
   ],
   "id": "t12-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.set_theme()\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "sns.countplot(data=df, x=\"category\")\n",
    "plt.title(\"Orders by category\")\n",
    "plt.show()"
   ],
   "id": "t12-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "### 7.3 Horizontal bars in a chosen order\n",
    "\n",
    "Change it and run: remove `order=order`. The bars are no longer sorted."
   ],
   "id": "t12-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "order = df[\"city\"].value_counts().index\n",
    "sns.countplot(data=df, y=\"city\", order=order, color=\"teal\")\n",
    "plt.title(\"Orders by city\")\n",
    "plt.show()"
   ],
   "id": "t12-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `y=\"city\"` instead of `x=\"city\"` draws horizontal bars.\n",
    "- `order=` takes a list of the group names in the order you want. `value_counts().index` is the list of cities from the most orders to the fewest.\n",
    "- `color=` sets the colour of the bars. One colour is enough here: the bars already have names, so different colours would add nothing.\n",
    "\n",
    "### 7.4 `barplot`: a summary of every group\n",
    "\n",
    "Change it and run: change `y=\"price\"` to `y=\"units\"`: the mean number of units of every category."
   ],
   "id": "t12-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.groupby(\"category\")[\"price\"].mean().round(2))\n",
    "\n",
    "sns.barplot(data=df, x=\"category\", y=\"price\", errorbar=None, color=\"teal\")\n",
    "plt.title(\"Mean price by category\")\n",
    "plt.show()"
   ],
   "id": "t12-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "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.\n",
    "\n",
    "For another summary, name it with `estimator`:\n",
    "\n",
    "Change it and run: change `estimator=\"sum\"` to `estimator=\"max\"`."
   ],
   "id": "t12-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "\n",
    "sns.barplot(data=df, x=\"category\", y=\"total\", estimator=\"sum\", errorbar=None, color=\"teal\")\n",
    "plt.title(\"Money by category\")\n",
    "plt.ylabel(\"Money\")\n",
    "plt.show()"
   ],
   "id": "t12-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`estimator=\"sum\"` draws the sum of every group. Other values are `\"median\"`, `\"max\"`, `\"min\"`.\n",
    "\n",
    "### 7.5 `histplot`: the spread of one column\n",
    "\n",
    "Change it and run: remove `kde=True`."
   ],
   "id": "t12-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.histplot(data=df, x=\"price\", bins=20, kde=True, color=\"teal\")\n",
    "plt.title(\"Prices of the orders\")\n",
    "plt.show()"
   ],
   "id": "t12-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 7.6 `boxplot`: the spread of every group\n",
    "\n",
    "Change it and run: change `x=\"category\"` to `x=\"city\"`."
   ],
   "id": "t12-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.boxplot(data=df, x=\"category\", y=\"price\", color=\"teal\")\n",
    "plt.title(\"Prices by category\")\n",
    "plt.show()"
   ],
   "id": "t12-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One line instead of the loop of Part 5. Seaborn made a box for every category and wrote the names on the axis.\n",
    "\n",
    "### 7.7 `scatterplot`: two number columns"
   ],
   "id": "t12-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "per_customer = df.groupby(\"customer\").agg(orders=(\"price\", \"size\"), money=(\"total\", \"sum\"))\n",
    "\n",
    "sns.scatterplot(data=per_customer, x=\"orders\", y=\"money\", color=\"teal\")\n",
    "plt.title(\"Customers: orders and money\")\n",
    "plt.show()"
   ],
   "id": "t12-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 7.8 `lineplot`: change over time\n",
    "\n",
    "Change it and run: remove `estimator=\"sum\"`. The line now shows the mean money of an order in every month."
   ],
   "id": "t12-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"month\"] = pd.to_datetime(df[\"date\"]).dt.month\n",
    "\n",
    "sns.lineplot(data=df, x=\"month\", y=\"total\", estimator=\"sum\", errorbar=None, marker=\"o\", color=\"teal\")\n",
    "plt.title(\"Money by month, 2025\")\n",
    "plt.ylabel(\"Money\")\n",
    "plt.xticks(range(1, 13))\n",
    "plt.show()"
   ],
   "id": "t12-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "## 8. Seaborn continued: groups in colour, heatmaps and more\n",
    "\n",
    "### 8.1 `hue`: a third column as colour\n",
    "\n",
    "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.\n",
    "\n",
    "Change it and run: change `hue=\"gender\"` to `hue=\"city\"`."
   ],
   "id": "t12-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.set_theme()\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "customers = pd.read_csv(\"customers.csv\")\n",
    "full = df.merge(customers, on=\"customer\", how=\"left\")\n",
    "\n",
    "sns.countplot(data=full, x=\"category\", hue=\"gender\")\n",
    "plt.title(\"Orders by category and gender\")\n",
    "plt.show()"
   ],
   "id": "t12-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "The gender is in the second file, so the two tables were joined first, as in the last lesson.\n",
    "\n",
    "`hue` works in the same way in a scatter chart:\n",
    "\n",
    "Change it and run: change `hue=\"category\"` to `hue=\"city\"`. Does the city explain the price?"
   ],
   "id": "t12-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.scatterplot(data=df, x=\"price\", y=\"units\", hue=\"category\", alpha=0.7)\n",
    "plt.title(\"Price and units of every order\")\n",
    "plt.show()"
   ],
   "id": "t12-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "A line for every group needs the same parameter. Here the money of every month, for two cities:\n",
    "\n",
    "Change it and run: use the cities `\"Sumqayit\"` and `\"Quba\"`."
   ],
   "id": "t12-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "df[\"month\"] = pd.to_datetime(df[\"date\"]).dt.month\n",
    "two = df[df[\"city\"].isin([\"Baku\", \"Ganja\"])]\n",
    "\n",
    "sns.lineplot(data=two, x=\"month\", y=\"total\", hue=\"city\", estimator=\"sum\", errorbar=None, marker=\"o\")\n",
    "plt.title(\"Money by month in two cities\")\n",
    "plt.ylabel(\"Money\")\n",
    "plt.xticks(range(1, 13))\n",
    "plt.show()"
   ],
   "id": "t12-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "And two histograms in one chart:\n",
    "\n",
    "Change it and run: compare `\"Home\"` and `\"Tech\"`."
   ],
   "id": "t12-083"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "two = df[df[\"category\"].isin([\"Books\", \"Clothing\"])]\n",
    "\n",
    "sns.histplot(data=two, x=\"price\", hue=\"category\", bins=20)\n",
    "plt.title(\"Prices of Books and Clothing\")\n",
    "plt.show()"
   ],
   "id": "t12-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The books are cheap and close together; the prices of Clothing are spread over a much wider range.\n",
    "\n",
    "### 8.2 `violinplot`: a box plot that shows the shape\n",
    "\n",
    "Change it and run: change `sns.violinplot` to `sns.boxplot` and compare the two charts."
   ],
   "id": "t12-085"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.violinplot(data=df, x=\"category\", y=\"price\", color=\"teal\")\n",
    "plt.title(\"Prices by category\")\n",
    "plt.show()"
   ],
   "id": "t12-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 8.3 `heatmap`: a table as colours\n",
    "\n",
    "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.\n",
    "\n",
    "Change it and run: change `cmap=\"Blues\"` to `cmap=\"Greens\"`, and remove `annot=True`."
   ],
   "id": "t12-087"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "table = pd.pivot_table(df, index=\"city\", columns=\"category\", values=\"price\", aggfunc=\"count\", fill_value=0)\n",
    "print(table)\n",
    "\n",
    "sns.heatmap(table, annot=True, fmt=\"d\", cmap=\"Blues\")\n",
    "plt.title(\"Orders by city and category\")\n",
    "plt.show()"
   ],
   "id": "t12-088"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `sns.heatmap` takes the table itself, not `data`, `x` and `y`: the table is already the summary.\n",
    "- `annot=True` writes the number into every cell, and `fmt=\"d\"` writes it as a whole number.\n",
    "- `cmap=\"Blues\"` is the colour scale: light for small numbers, dark for large ones.\n",
    "- `fill_value=0` in `pivot_table` writes 0 where a city has no orders of a category. Without it the cell would be a missing value.\n",
    "\n",
    "The dark cells are found at once: Baku buys the most in every category, and Sumqayit buys a lot of Tech.\n",
    "\n",
    "### 8.4 A heatmap of correlations\n",
    "\n",
    "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.\n",
    "\n",
    "Change it and run: remove `vmin=-1, vmax=1`. The colours change, the numbers do not."
   ],
   "id": "t12-089"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "corr = df[[\"price\", \"units\", \"rating\"]].corr().round(2)\n",
    "print(corr)\n",
    "\n",
    "sns.heatmap(corr, annot=True, cmap=\"coolwarm\", vmin=-1, vmax=1)\n",
    "plt.title(\"Correlations\")\n",
    "plt.show()"
   ],
   "id": "t12-090"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "This chart is used in almost every machine learning project to see which columns are related.\n",
    "\n",
    "### 8.5 `regplot`: a scatter chart with a trend line\n",
    "\n",
    "Change it and run: remove `ci=None`. A shaded band appears around the line."
   ],
   "id": "t12-091"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "per_customer = df.groupby(\"customer\").agg(orders=(\"price\", \"size\"), money=(\"total\", \"sum\"))\n",
    "\n",
    "sns.regplot(data=per_customer, x=\"orders\", y=\"money\", ci=None, color=\"teal\")\n",
    "plt.title(\"Customers: orders and money\")\n",
    "plt.show()"
   ],
   "id": "t12-092"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "### 8.6 `pairplot`: every pair of number columns at once\n",
    "\n",
    "Change it and run: leave out `\"rating\"`: only two columns."
   ],
   "id": "t12-093"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.pairplot(df[[\"price\", \"units\", \"rating\"]], height=2)\n",
    "plt.show()"
   ],
   "id": "t12-094"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "`pairplot` makes its own figure, so `plt.figure(figsize=...)` does not change its size. Use its parameter `height` (the size of one small chart).\n",
    "\n",
    "### 8.7 Seaborn inside `plt.subplots`\n",
    "\n",
    "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.\n",
    "\n",
    "Change it and run: draw the column `units` in the second chart."
   ],
   "id": "t12-095"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(1, 2, figsize=(11, 4))\n",
    "\n",
    "sns.histplot(data=df, x=\"price\", bins=20, color=\"teal\", ax=axes[0])\n",
    "axes[0].set_title(\"Prices of the orders\")\n",
    "\n",
    "sns.countplot(data=df, x=\"rating\", color=\"teal\", ax=axes[1])\n",
    "axes[1].set_title(\"Ratings\")\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ],
   "id": "t12-096"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The ratings are missing in 36 orders. Seaborn leaves these rows out, so the bars show the 264 orders that have a rating.\n",
    "\n",
    "## 9. Choosing the right chart\n",
    "\n",
    "Start from the question, not from the chart.\n",
    "\n",
    "| The question | The columns | The chart | Matplotlib | Seaborn |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| How does it change over time? | time and a number | line | `plt.plot` | `sns.lineplot` |\n",
    "| How many rows has every group? | one text column | bar | `value_counts`, then `plt.bar` | `sns.countplot` |\n",
    "| How do the groups compare in a number? | a text and a number column | bar | `groupby`, then `plt.bar` | `sns.barplot` |\n",
    "| Where are most of the values? | one number column | histogram | `plt.hist` | `sns.histplot` |\n",
    "| How wide is the spread, are there outliers? | a number column (and a text column) | box plot | `plt.boxplot` | `sns.boxplot`, `sns.violinplot` |\n",
    "| Do two numbers move together? | two number columns | scatter | `plt.scatter` | `sns.scatterplot`, `sns.regplot` |\n",
    "| What share of the whole? | 2 to 4 groups | pie | `plt.pie` | (use Matplotlib) |\n",
    "| Two groupings at once? | two text columns | grouped bars or heatmap |  | `hue=`, `sns.heatmap` |\n",
    "| Which number columns are related? | several number columns | heatmap of `corr()` |  | `sns.heatmap`, `sns.pairplot` |\n",
    "\n",
    "### 9.1 Matplotlib or Seaborn?\n",
    "\n",
    "- 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 `hue` gives groups in colour.\n",
    "- 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.\n",
    "\n",
    "In practice you use both in the same cell: Seaborn draws, Matplotlib finishes.\n",
    "\n",
    "### 9.2 A checklist for every chart\n",
    "\n",
    "1. One question for one chart. Say the question before you draw.\n",
    "2. A title and axis labels, with the unit where there is one.\n",
    "3. Sorted bars, unless the groups have their own order (months, ratings).\n",
    "4. Colour only where it means something.\n",
    "5. Honest axes: bars start at 0.\n",
    "6. Look at the numbers behind the chart at least once (`print` the summary).\n",
    "\n",
    "### 9.3 From a question to a chart\n",
    "\n",
    "Question: in which months does the shop earn the most, and is it the same for every category?\n",
    "\n",
    "Change it and run: add `annot=True, fmt=\".0f\"` to `sns.heatmap`."
   ],
   "id": "t12-097"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.set_theme()\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "df[\"month\"] = pd.to_datetime(df[\"date\"]).dt.month\n",
    "\n",
    "table = pd.pivot_table(df, index=\"category\", columns=\"month\", values=\"total\", aggfunc=\"sum\", fill_value=0)\n",
    "print(table.round(0).astype(int))\n",
    "\n",
    "plt.figure(figsize=(10, 3.5))\n",
    "sns.heatmap(table, cmap=\"Blues\")\n",
    "plt.title(\"Money by category and month, 2025\")\n",
    "plt.show()"
   ],
   "id": "t12-098"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "## 10. Common mistakes\n",
    "\n",
    "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.\n",
    "\n",
    "`import matplotlib as plt`. The drawing functions are in `matplotlib.pyplot`, not in `matplotlib` itself.\n",
    "\n",
    "```python\n",
    "import matplotlib as plt\n",
    "\n",
    "plt.plot([3, 5, 4, 8])\n",
    "```\n",
    "\n",
    "```\n",
    "AttributeError: module 'matplotlib' has no attribute 'plot'\n",
    "```\n",
    "\n",
    "Write `import matplotlib.pyplot as plt`.\n",
    "\n",
    "x and y of different lengths. Every x needs its y.\n",
    "\n",
    "```python\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "days = [1, 2, 3, 4, 5]\n",
    "visitors = [120, 135, 128, 160]\n",
    "\n",
    "plt.plot(days, visitors)\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: x and y must have same first dimension, but have shapes (5,) and (4,)\n",
    "```\n",
    "\n",
    "Count the values: there are 5 days and 4 numbers of visitors.\n",
    "\n",
    "A wrong column name in Seaborn. The names are case-sensitive, as in pandas.\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "sns.barplot(data=df, x=\"Category\", y=\"price\")\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: Could not interpret value `Category` for `x`. An entry with this name does not appear in `data`.\n",
    "```\n",
    "\n",
    "The column is called `category`. Check the names with `df.columns`.\n",
    "\n",
    "Two charts drawn into one. Without `plt.show()` (or `plt.figure()`) between them, the second chart is drawn on top of the first."
   ],
   "id": "t12-099"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "\n",
    "plt.hist(df[\"price\"], bins=20)\n",
    "plt.title(\"Prices\")\n",
    "\n",
    "plt.hist(df[\"rating\"], bins=5)\n",
    "plt.title(\"Ratings\")\n",
    "plt.show()"
   ],
   "id": "t12-100"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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:"
   ],
   "id": "t12-101"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "\n",
    "plt.hist(df[\"price\"], bins=20)\n",
    "plt.title(\"Prices\")\n",
    "plt.show()\n",
    "\n",
    "plt.hist(df[\"rating\"], bins=5)\n",
    "plt.title(\"Ratings\")\n",
    "plt.show()"
   ],
   "id": "t12-102"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A bar chart of rows that are not summarised. `plt.bar` draws one bar for every value it gets."
   ],
   "id": "t12-103"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "\n",
    "plt.bar(df[\"category\"], df[\"price\"])\n",
    "plt.title(\"Price by category?\")\n",
    "plt.show()"
   ],
   "id": "t12-104"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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:"
   ],
   "id": "t12-105"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "mean_price = df.groupby(\"category\")[\"price\"].mean()\n",
    "\n",
    "plt.bar(mean_price.index, mean_price.values)\n",
    "plt.title(\"Mean price by category\")\n",
    "plt.show()"
   ],
   "id": "t12-106"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A line chart for groups without an order."
   ],
   "id": "t12-107"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "counts = df[\"city\"].value_counts()\n",
    "\n",
    "plt.plot(counts.index, counts.values)\n",
    "plt.title(\"Orders by city\")\n",
    "plt.show()"
   ],
   "id": "t12-108"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "A pie chart with many slices."
   ],
   "id": "t12-109"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "counts = df[\"product\"].value_counts()\n",
    "\n",
    "plt.pie(counts.values, labels=counts.index)\n",
    "plt.title(\"Orders by product\")\n",
    "plt.show()"
   ],
   "id": "t12-110"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Nobody can compare these slices. A sorted `plt.barh` of the same numbers is read in a second.\n",
    "\n",
    "More mistakes in short:\n",
    "\n",
    "| Mistake | What happens | Fix |\n",
    "| --- | --- | --- |\n",
    "| 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()` |\n",
    "| `plt.savefig` after `plt.show()` | an empty picture is saved | save first, then show |\n",
    "| `plt.figure(figsize=...)` after the drawing | a second, empty chart appears | write it before the drawing |\n",
    "| `plt.legend()` without `label=` | an empty legend and a warning | give every line a `label` |\n",
    "| No title and no axis labels | the reader has to guess | `plt.title`, `plt.xlabel`, `plt.ylabel` |\n",
    "| 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 |\n",
    "| `sns.barplot` without `estimator` when you want sums | the bars show means | `estimator=\"sum\"` |\n",
    "| Bars that do not start at 0 (`plt.ylim(100, 130)`) | small differences look huge | let bars start at 0 |\n",
    "\n",
    "## 11. Solved problems (easy to medium-hard)\n",
    "\n",
    "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.\n",
    "\n",
    "### 11.1 Level 1: Easy\n",
    "\n",
    "Problem 1. The temperatures of a week\n",
    "\n",
    "Draw the temperatures of seven days as a line with markers. Add a title and axis labels.\n",
    "\n",
    "Change it and run: add an eighth day, Mon with 17 degrees. What happens to the axis?"
   ],
   "id": "t12-111"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "days = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\n",
    "temps = [18, 21, 19, 24, 26, 23, 20]\n",
    "\n",
    "plt.plot(days, temps, marker=\"o\", color=\"tomato\")\n",
    "plt.title(\"Temperature of the week\")\n",
    "plt.xlabel(\"Day\")\n",
    "plt.ylabel(\"Degrees\")\n",
    "plt.show()"
   ],
   "id": "t12-112"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 2. The grades of five students\n",
    "\n",
    "Draw the grades as bars, sorted from the highest to the lowest.\n",
    "\n",
    "Change it and run: sort from the lowest to the highest grade."
   ],
   "id": "t12-113"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "grades = pd.Series({\"Aylin\": 85, \"Murad\": 72, \"Leyla\": 91, \"Kamran\": 64, \"Nigar\": 78})\n",
    "grades = grades.sort_values(ascending=False)\n",
    "print(grades)\n",
    "\n",
    "plt.bar(grades.index, grades.values, color=\"teal\")\n",
    "plt.title(\"Exam grades\")\n",
    "plt.ylabel(\"Grade\")\n",
    "plt.show()"
   ],
   "id": "t12-114"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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`.\n",
    "\n",
    "Problem 3. Two curves and a legend\n",
    "\n",
    "Draw `y = x` and `y = x squared` for x from 0 to 3 in one chart, with a legend.\n",
    "\n",
    "Change it and run: add a third curve, `x ** 3`, with a dotted line."
   ],
   "id": "t12-115"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "x = np.linspace(0, 3, 40)\n",
    "\n",
    "plt.plot(x, x, label=\"y = x\")\n",
    "plt.plot(x, x ** 2, label=\"y = x squared\", linestyle=\"--\")\n",
    "plt.title(\"Two functions\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"y\")\n",
    "plt.legend()\n",
    "plt.grid(True)\n",
    "plt.show()"
   ],
   "id": "t12-116"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: Two `plt.plot` calls, one chart. The grid shows where the curves cross: at x = 1 both are 1.\n",
    "\n",
    "Problem 4. How many units are in an order?\n",
    "\n",
    "Draw how many orders have 1, 2, 3, 4 and 5 units.\n",
    "\n",
    "Change it and run: remove `.sort_index()`. The bars keep their places, because the x values are numbers."
   ],
   "id": "t12-117"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "counts = df[\"units\"].value_counts().sort_index()\n",
    "print(counts)\n",
    "\n",
    "plt.bar(counts.index, counts.values, color=\"teal\")\n",
    "plt.title(\"Units in an order\")\n",
    "plt.xlabel(\"Units\")\n",
    "plt.ylabel(\"Orders\")\n",
    "plt.show()"
   ],
   "id": "t12-118"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 5. The ratings\n",
    "\n",
    "Draw how many orders got each rating, with Seaborn.\n",
    "\n",
    "Change it and run: add `hue=\"category\"`."
   ],
   "id": "t12-119"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.set_theme()\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df[\"rating\"].value_counts().sort_index())\n",
    "\n",
    "sns.countplot(data=df, x=\"rating\", color=\"teal\")\n",
    "plt.title(\"Ratings of the orders\")\n",
    "plt.show()"
   ],
   "id": "t12-120"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 11.2 Level 2: Medium\n",
    "\n",
    "Problem 6. The five best customers\n",
    "\n",
    "Draw the money of the five customers who spent the most, as horizontal bars with the best at the top.\n",
    "\n",
    "Change it and run: show the ten best customers."
   ],
   "id": "t12-121"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "best = df.groupby(\"customer\")[\"total\"].sum().sort_values().tail(5)\n",
    "print(best)\n",
    "\n",
    "plt.barh(best.index, best.values, color=\"teal\")\n",
    "plt.title(\"The five best customers\")\n",
    "plt.xlabel(\"Money spent\")\n",
    "plt.show()"
   ],
   "id": "t12-122"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: Sorted from small to large, the last five rows are the five largest, and `barh` draws the last one at the top.\n",
    "\n",
    "Problem 7. Orders and money by month\n",
    "\n",
    "Draw the money of every month as a line. Mark the best month in the title.\n",
    "\n",
    "Change it and run: draw the number of orders instead of the money."
   ],
   "id": "t12-123"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "df[\"month\"] = pd.to_datetime(df[\"date\"]).dt.month\n",
    "money = df.groupby(\"month\")[\"total\"].sum()\n",
    "best = money.idxmax()\n",
    "print(money.round(2).tolist())\n",
    "print(best)\n",
    "\n",
    "plt.plot(money.index, money.values, marker=\"o\", color=\"teal\")\n",
    "plt.title(f\"Money by month (the best month: {best})\")\n",
    "plt.xlabel(\"Month\")\n",
    "plt.ylabel(\"Money\")\n",
    "plt.xticks(range(1, 13))\n",
    "plt.grid(True)\n",
    "plt.show()"
   ],
   "id": "t12-124"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: A title is text, so an f-string can put a calculated value into it.\n",
    "\n",
    "Problem 8. The prices of two categories\n",
    "\n",
    "Compare how the prices of Books and Tech are spread: two histograms in one chart.\n",
    "\n",
    "Change it and run: compare `\"Home\"` and `\"Clothing\"`."
   ],
   "id": "t12-125"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "books = df[df[\"category\"] == \"Books\"][\"price\"]\n",
    "tech = df[df[\"category\"] == \"Tech\"][\"price\"]\n",
    "print(round(books.median(), 2), round(tech.median(), 2))\n",
    "\n",
    "plt.hist(books, bins=15, alpha=0.6, label=\"Books\")\n",
    "plt.hist(tech, bins=15, alpha=0.6, label=\"Tech\")\n",
    "plt.title(\"Prices of Books and Tech\")\n",
    "plt.xlabel(\"Price\")\n",
    "plt.ylabel(\"Orders\")\n",
    "plt.legend()\n",
    "plt.show()"
   ],
   "id": "t12-126"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 9. The mean rating of every category\n",
    "\n",
    "Draw the mean rating of every category with Seaborn. The scale of a rating is 1 to 5: show the whole scale.\n",
    "\n",
    "Change it and run: change `plt.ylim(0, 5)` to `plt.ylim(3.9, 4.2)`. The same numbers now look very different."
   ],
   "id": "t12-127"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.set_theme()\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.groupby(\"category\")[\"rating\"].mean().round(2))\n",
    "\n",
    "sns.barplot(data=df, x=\"category\", y=\"rating\", errorbar=None, color=\"teal\")\n",
    "plt.title(\"Mean rating by category\")\n",
    "plt.ylim(0, 5)\n",
    "plt.show()"
   ],
   "id": "t12-128"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 10. Which city pays the most for an order?\n",
    "\n",
    "Compare the prices of the cities with box plots, the cities in the order of their median price.\n",
    "\n",
    "Change it and run: draw the column `rating` instead of `price`."
   ],
   "id": "t12-129"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.set_theme()\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "medians = df.groupby(\"city\")[\"price\"].median().sort_values(ascending=False)\n",
    "print(medians.round(2))\n",
    "\n",
    "sns.boxplot(data=df, x=\"city\", y=\"price\", order=medians.index, color=\"teal\")\n",
    "plt.title(\"Prices by city\")\n",
    "plt.show()"
   ],
   "id": "t12-130"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 11.3 Level 3: Medium-Hard\n",
    "\n",
    "Problem 11. Two charts side by side\n",
    "\n",
    "Show the number of orders and the money of every category next to each other, with the same order of the categories.\n",
    "\n",
    "Change it and run: sort the table by `\"orders\"` instead of `\"money\"`."
   ],
   "id": "t12-131"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "summary = df.groupby(\"category\").agg(orders=(\"price\", \"size\"), money=(\"total\", \"sum\")).sort_values(\"money\")\n",
    "print(summary)\n",
    "\n",
    "fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))\n",
    "\n",
    "axes[0].barh(summary.index, summary[\"orders\"], color=\"gray\")\n",
    "axes[0].set_title(\"Orders\")\n",
    "\n",
    "axes[1].barh(summary.index, summary[\"money\"], color=\"teal\")\n",
    "axes[1].set_title(\"Money\")\n",
    "\n",
    "fig.suptitle(\"Categories: orders and money\")\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ],
   "id": "t12-132"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 12. Cheap products are bought in larger numbers\n",
    "\n",
    "Show the mean price of the orders with 1, 2, 3, 4 and 5 units.\n",
    "\n",
    "Change it and run: use `estimator=\"median\"`."
   ],
   "id": "t12-133"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.set_theme()\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.groupby(\"units\")[\"price\"].mean().round(1))\n",
    "\n",
    "sns.barplot(data=df, x=\"units\", y=\"price\", errorbar=None, color=\"teal\")\n",
    "plt.title(\"Mean price by the number of units\")\n",
    "plt.ylabel(\"Mean price\")\n",
    "plt.show()"
   ],
   "id": "t12-134"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 13. Money by category and gender\n",
    "\n",
    "Join the orders with the customers and draw the money of every category, split by gender.\n",
    "\n",
    "Change it and run: change `hue=\"gender\"` to `hue=\"city\"`."
   ],
   "id": "t12-135"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.set_theme()\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "customers = pd.read_csv(\"customers.csv\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "full = df.merge(customers, on=\"customer\", how=\"left\")\n",
    "print(full.groupby([\"category\", \"gender\"])[\"total\"].sum().round(0))\n",
    "\n",
    "sns.barplot(data=full, x=\"category\", y=\"total\", hue=\"gender\", estimator=\"sum\", errorbar=None)\n",
    "plt.title(\"Money by category and gender\")\n",
    "plt.ylabel(\"Money\")\n",
    "plt.show()"
   ],
   "id": "t12-136"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 14. Do older customers spend more?\n",
    "\n",
    "Make one row for every customer with the age and the money spent, and draw them against each other with a trend line.\n",
    "\n",
    "Change it and run: add `ci=None` again after removing it, and compare."
   ],
   "id": "t12-137"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.set_theme()\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "customers = pd.read_csv(\"customers.csv\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "money = df.groupby(\"customer\")[\"total\"].sum().reset_index()\n",
    "table = customers.merge(money, on=\"customer\")\n",
    "print(table.shape)\n",
    "print(table[[\"age\", \"total\"]].corr().round(2))\n",
    "\n",
    "sns.regplot(data=table, x=\"age\", y=\"total\", ci=None, color=\"teal\")\n",
    "plt.title(\"Age and money spent\")\n",
    "plt.ylabel(\"Money spent\")\n",
    "plt.show()"
   ],
   "id": "t12-138"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 15. Four charts about the shop\n",
    "\n",
    "Make one figure with four charts: the prices (histogram), the money by category (bars), the orders by month (line) and the ratings (bars).\n",
    "\n",
    "Change it and run: put the box plot `sns.boxplot(data=df, x=\"category\", y=\"price\", ax=axes[1, 1])` into the last chart."
   ],
   "id": "t12-139"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.set_theme()\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "df[\"month\"] = pd.to_datetime(df[\"date\"]).dt.month\n",
    "monthly = df.groupby(\"month\").size()\n",
    "order = df.groupby(\"category\")[\"total\"].sum().sort_values(ascending=False).index\n",
    "\n",
    "fig, axes = plt.subplots(2, 2, figsize=(11, 7))\n",
    "\n",
    "sns.histplot(data=df, x=\"price\", bins=20, color=\"teal\", ax=axes[0, 0])\n",
    "axes[0, 0].set_title(\"Prices\")\n",
    "\n",
    "sns.barplot(data=df, x=\"category\", y=\"total\", estimator=\"sum\", errorbar=None, order=order, color=\"teal\", ax=axes[0, 1])\n",
    "axes[0, 1].set_title(\"Money by category\")\n",
    "axes[0, 1].set_ylabel(\"Money\")\n",
    "\n",
    "axes[1, 0].plot(monthly.index, monthly.values, marker=\"o\", color=\"teal\")\n",
    "axes[1, 0].set_title(\"Orders by month\")\n",
    "axes[1, 0].set_xticks(range(1, 13))\n",
    "\n",
    "sns.countplot(data=df, x=\"rating\", color=\"teal\", ax=axes[1, 1])\n",
    "axes[1, 1].set_title(\"Ratings\")\n",
    "\n",
    "fig.suptitle(\"The shop in 2025\")\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ],
   "id": "t12-140"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "## 14. Quick summary\n",
    "\n",
    "| Task | Code |\n",
    "| --- | --- |\n",
    "| Import | `import matplotlib.pyplot as plt`, `import seaborn as sns` |\n",
    "| A line | `plt.plot(x, y, color=\"teal\", linestyle=\"--\", marker=\"o\")` |\n",
    "| Describe the chart | `plt.title(\"...\")`, `plt.xlabel(\"...\")`, `plt.ylabel(\"...\")` |\n",
    "| Several lines | one `plt.plot(..., label=\"...\")` for each, then `plt.legend()` |\n",
    "| Size, grid | `plt.figure(figsize=(8, 3))` before the drawing, `plt.grid(True)` |\n",
    "| Limits, ticks | `plt.ylim(0, 200)`, `plt.xticks(positions, names)` |\n",
    "| Save, show | `plt.savefig(\"name.png\")`, then `plt.show()` |\n",
    "| Bars | `plt.bar(names, values)`, `plt.barh(names, values)` |\n",
    "| Histogram | `plt.hist(values, bins=20)` |\n",
    "| Scatter | `plt.scatter(x, y, alpha=0.5)` |\n",
    "| Box plot | `plt.boxplot([list1, list2])` |\n",
    "| Pie | `plt.pie(values, labels=names, autopct=\"%1.0f%%\")` |\n",
    "| Several charts | `fig, axes = plt.subplots(1, 2)`, `axes[0].plot(...)`, `axes[0].set_title(...)`, `plt.tight_layout()` |\n",
    "| A summary as a chart | `s = df[\"city\"].value_counts()`, then `plt.bar(s.index, s.values)` |\n",
    "| The pandas shortcut | `s.plot(kind=\"bar\")` |\n",
    "| Seaborn from lists | `sns.lineplot(x=days, y=visitors)`, `sns.barplot(x=names, y=values)` |\n",
    "| The Seaborn look | `sns.set_theme()` |\n",
    "| Rows of every group | `sns.countplot(data=df, x=\"city\")` |\n",
    "| A summary of every group | `sns.barplot(data=df, x=\"category\", y=\"price\", estimator=\"sum\", errorbar=None)` |\n",
    "| Spread of one column | `sns.histplot(data=df, x=\"price\", bins=20, kde=True)` |\n",
    "| Spread of every group | `sns.boxplot(data=df, x=\"category\", y=\"price\")`, `sns.violinplot(...)` |\n",
    "| Two number columns | `sns.scatterplot(data=df, x=\"price\", y=\"units\")`, `sns.regplot(...)` |\n",
    "| Change over time | `sns.lineplot(data=df, x=\"month\", y=\"total\", estimator=\"sum\", errorbar=None)` |\n",
    "| Groups in colour | `hue=\"gender\"` |\n",
    "| A table as colours | `sns.heatmap(table, annot=True, cmap=\"Blues\")` |\n",
    "| All pairs of columns | `sns.pairplot(df[[\"price\", \"units\", \"rating\"]])` |\n",
    "| A Seaborn chart in a figure | `sns.histplot(..., ax=axes[0])` |\n",
    "\n",
    "Golden rules\n",
    "\n",
    "1. Start from the question; the question chooses the chart.\n",
    "2. Line for time, bars for groups, histogram for one number column, scatter for two number columns, box plot for spread and outliers.\n",
    "3. Summarise first (`value_counts`, `groupby`), look at the numbers, then draw.\n",
    "4. Draw, describe, show: every chart gets a title and axis labels and ends with `plt.show()`.\n",
    "5. Seaborn draws from a table with `data`, `x`, `y` and `hue`; Matplotlib finishes the chart.\n",
    "6. Sorted bars, honest axes, colour only where it means something.\n",
    "\n",
    "Next: the practice notebook (topic-12-practice.ipynb), then Topic 13: Linear Algebra: vectors and vector operations (addition, dot product)."
   ],
   "id": "t12-141"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
