{"cells":[{"cell_type":"markdown","metadata":{"id":"hw3-00"},"source":["# Homework 3: Visualizing Data Using Matplotlib\n","\n","Welcome! This notebook will guide you from reading the question to submitting\n","your answer. You do not need to finish everything at once. Work from the top of\n","the notebook to the bottom, and run each code cell in order.\n","\n","## Deadline\n","\n","Thu, Oct 22, 2026 (11:00 UTC)\n","\n","## Recommended workflow\n","\n","1. Read the question and the expected input/output carefully.\n","2. Run the cells in **1. Preparation**.\n","3. Complete only the `homework()` function in **2. Your Answer**.\n","4. Run the cases in **3. Test Your Answer** and compare the results.\n","5. Copy the complete `homework()` function and submit it in Omnicampus.\n","\n","If you change your function, run its cell again before running the later cells.\n"],"id":"hw3-00"},{"cell_type":"markdown","metadata":{"id":"hw3-01"},"source":["## Question\n","\n","Your task is to perform a **Pareto analysis** (decile analysis) on a dataset from MyAnimeList [1], a popular anime database containing information on over 17,000 anime titles.\n","\n","Using the downloaded and preprocessed data (see Section 1), `anime_data`, write a function that performs the following steps:\n","\n","1. **Sort Anime by the Given Metric:**\n"," - Sort the anime in descending order based on the values in the column specified by `metric_column`.\n","\n","2. **Group Anime into $n$ Equal Parts:**\n"," - Without changing the sorted order, divide the anime into $n$ groups of equal size.\n"," - $n$ is a natural number (positive integer).\n"," - Use `pd.qcut()` on the rank of the metric values (with `method='first'`) to handle grouping. This avoids issues with duplicate values.\n","\n","3. **Calculate Proportion for Each Group:**\n"," - For each group, calculate what percentage of the **overall total** (of `metric_column`) that group represents.\n"," - This is known as **decile analysis** when $n = 10$, but works for any valid $n$.\n","\n","4. **Sort Groups and Label:**\n"," - Sort the groups in descending order of their proportion.\n"," - Label them as `\"Group 1\"`, `\"Group 2\"`, ..., `\"Group n\"`.\n"," - Return the result as a `pandas.Series`.\n","\n","
\n","\n","**Background:**
\n","The **Pareto Principle** states that roughly 80% of effects come from 20% of causes. In the anime context, a small number of highly popular anime may account for the vast majority of total viewership. This principle is widely used in business, marketing, and data analysis.\n","\n","
\n","\n","**Inputs / Outputs:**
\n","\n","```\n","homework(anime_data: pd.DataFrame, metric_column: str, n: int) -> pd.Series\n","```\n","\n","| Argument | Type | Description |\n","|---|---|---|\n","| `anime_data` | `pd.DataFrame` | Preprocessed anime dataset (see Section 1) |\n","| `metric_column` | `str` | Column name to analyze, e.g. `'Completed'`, `'Members'` |\n","| `n` | `int` | Number of groups to divide into |\n","\n","| Return | Type | Description |\n","|---|---|---|\n","| result | `pd.Series` | Proportions per group, sorted descending, index = `\"Group 1\"` ... `\"Group n\"`, values sum to 1.0 |\n","\n","**Example:**
\n","\n","```python\n","result = homework(anime_data, 'Completed', 5)\n","print(result)\n","```\n","```\n","Group 1 0.94XXXX\n","Group 2 0.04XXXX\n","Group 3 0.009XXX\n","Group 4 0.001XXX\n","Group 5 0.0004XX\n","dtype: float64\n","```\n","\n","**Note:**
\n","- Submit **only** the `homework()` function to Omnicampus.\n","- Erase `# Write your answer here` before submitting.\n","- Do **NOT** include `import` statements in your submission.\n","- Do **NOT** modify the preprocessing cell (Section 1).\n","- Return type must be `pd.Series` with values summing to 1.0."],"id":"hw3-01"},{"cell_type":"markdown","metadata":{"id":"hw3-02"},"source":["## 1. Preparation\n","\n","Run the next three cells in order. They import the required libraries,\n","download the MyAnimeList dataset, and preprocess the columns used in this\n","assignment.\n","\n","Do not modify the preprocessing cell, and do not copy import, download, or\n","loading code into `homework()`.\n"],"id":"hw3-02"},{"cell_type":"code","execution_count":null,"metadata":{"id":"hw3-03"},"outputs":[],"source":["import numpy as np\n","import pandas as pd\n","import matplotlib.pyplot as plt\n","import requests\n","import zipfile\n","import io"],"id":"hw3-03"},{"cell_type":"code","execution_count":null,"metadata":{"id":"hw3-04"},"outputs":[],"source":["# Download MyAnimeList data from GitHub\n","url = 'https://github.com/Hernan4444/MyAnimeList-Database/archive/refs/heads/master.zip'\n","r = requests.get(url, stream=True)\n","z = zipfile.ZipFile(io.BytesIO(r.content))\n","z.extractall()\n","\n","# Load the anime data\n","anime_data_raw = pd.read_csv('MyAnimeList-Database-master/data/anime.csv')\n","print(f\"Raw dataset shape: {anime_data_raw.shape}\")\n","anime_data_raw.head()"],"id":"hw3-04"},{"cell_type":"code","execution_count":null,"metadata":{"id":"hw3-05"},"outputs":[],"source":["# Preprocessing — Do NOT modify this cell\n","columns_to_keep = ['MAL_ID', 'Name', 'Score', 'Type', 'Episodes',\n"," 'Members', 'Completed', 'Watching', 'Dropped', 'Popularity']\n","anime_data = anime_data_raw[columns_to_keep].copy()\n","\n","# Remove rows where key metric columns have missing or zero values\n","anime_data = anime_data.dropna(subset=['Members', 'Completed', 'Watching'])\n","anime_data = anime_data[(anime_data['Members'] > 0) &\n"," (anime_data['Completed'] > 0) &\n"," (anime_data['Watching'] > 0)]\n","anime_data = anime_data.reset_index(drop=True)\n","print(f\"Dataset shape after preprocessing: {anime_data.shape}\")\n","anime_data.head()"],"id":"hw3-05"},{"cell_type":"markdown","metadata":{"id":"hw3-06"},"source":["## 2. Your Answer\n","\n","Complete the `homework()` function below.\n","\n","- Keep the function name and parameters unchanged.\n","- Write your code at `# Write your answer here`.\n","- Do **not** put `import` statements, file downloads, or data-loading code\n"," inside the function.\n","- Make sure the function returns the requested result.\n","\n","The temporary value `None` only keeps the starter cell runnable. Replace it\n","with your own code before testing and submitting.\n"],"id":"hw3-06"},{"cell_type":"code","execution_count":null,"metadata":{"id":"hw3-07"},"outputs":[],"source":["def homework(anime_data, metric_column, n):\n"," # Write your answer here\n"," my_result = None\n"," return my_result\n"],"id":"hw3-07"},{"cell_type":"markdown","metadata":{"id":"hw3-08"},"source":["## 3. Test Your Answer\n","\n","Run each test case after completing `homework()`. Trying more than one input\n","makes it easier to find mistakes and increases confidence in your answer.\n","\n","> **Important:** Matching all examples below does **not** guarantee a correct\n","> answer or a full score. Omnicampus uses additional grading cases that are not\n","> shown in this notebook.\n"],"id":"hw3-08"},{"cell_type":"markdown","metadata":{"id":"hw3-09"},"source":["### Test Case 1: Full prepared dataset\n"],"id":"hw3-09"},{"cell_type":"code","execution_count":null,"metadata":{"id":"hw3-10"},"outputs":[],"source":["# Run this cell after completing homework().\n","your_answer = homework(anime_data, \"Completed\", 10)\n","display(your_answer)\n"],"id":"hw3-10"},{"cell_type":"markdown","metadata":{"id":"hw3-11"},"source":["For this example, your answer is correct if it is a\n","`pd.Series` with 10 rows named `Group 1` through `Group 10`, the proportions\n","are ordered from largest to smallest, and the values add up to approximately\n","`1.0`.\n","\n","This confirms only `metric_column=\"Completed\"` and `n=10`. The grader also\n","uses other columns and other values of `n`.\n"],"id":"hw3-11"},{"cell_type":"markdown","metadata":{"id":"hw3-12"},"source":["### Test Case 2: Four rows divided into two groups\n"],"id":"hw3-12"},{"cell_type":"code","execution_count":null,"metadata":{"id":"hw3-13"},"outputs":[],"source":["case_2_data = pd.DataFrame({\n"," \"Completed\": [40, 30, 20, 10],\n","})\n","case_2_answer = homework(case_2_data, \"Completed\", 2)\n","display(case_2_answer)\n"],"id":"hw3-13"},{"cell_type":"markdown","metadata":{"id":"hw3-14"},"source":["The expected proportions are:\n","\n","```text\n","Group 1 0.7\n","Group 2 0.3\n","dtype: float64\n","```\n"],"id":"hw3-14"},{"cell_type":"markdown","metadata":{"id":"hw3-15"},"source":["### Test Case 3: Six rows divided into three groups\n"],"id":"hw3-15"},{"cell_type":"code","execution_count":null,"metadata":{"id":"hw3-16"},"outputs":[],"source":["case_3_data = pd.DataFrame({\n"," \"Members\": [60, 50, 40, 30, 20, 10],\n","})\n","case_3_answer = homework(case_3_data, \"Members\", 3)\n","display(case_3_answer)\n"],"id":"hw3-16"},{"cell_type":"markdown","metadata":{"id":"hw3-17"},"source":["The expected proportions are approximately:\n","\n","```text\n","Group 1 0.523810\n","Group 2 0.333333\n","Group 3 0.142857\n","dtype: float64\n","```\n"],"id":"hw3-17"},{"cell_type":"markdown","metadata":{"id":"hw3-18"},"source":["### Final checklist\n","\n","Before moving to Section 4, check the following:\n","\n","- You kept the function name and parameters unchanged.\n","- Your function returns the requested result.\n","- There are no `import` statements inside `homework()`.\n","- There is no file download or data-loading code inside `homework()`.\n","- You ran the `homework()` cell again after your latest edit.\n","- You compared the output of every test case with its expected result.\n"],"id":"hw3-18"},{"cell_type":"markdown","metadata":{"id":"hw3-19"},"source":["### Optional: Visualize the Result\n","\n","Let's create a **Pareto chart** to visualize the result of your analysis.\n","\n","Notice how the top groups account for the majority of the total — this is the Pareto Principle in action!"],"id":"hw3-19"},{"cell_type":"code","execution_count":null,"metadata":{"id":"hw3-20"},"outputs":[],"source":["N = 10\n","data = homework(anime_data, 'Completed', N)\n","\n","fig, ax1 = plt.subplots(figsize=(8, 5))\n","\n","data_num = len(data)\n","cum_per = np.cumsum(data)\n","\n","# Bar chart — proportion per group\n","ax1.bar(range(data_num), data, color='steelblue', edgecolor='white')\n","ax1.set_xticks(range(data_num))\n","ax1.set_xticklabels(data.index, rotation=45, ha='right')\n","\n","# Line chart — cumulative proportion\n","ax2 = ax1.twinx()\n","ax2.plot(range(data_num), cum_per, color='k', marker='o', linewidth=2)\n","ax2.set_ylim([0, 1.05])\n","ax2.axhline(y=0.8, color='r', linestyle='--', alpha=0.5, label='80% line')\n","ax2.grid(True, which='both', axis='y', alpha=0.3)\n","\n","ax1.set_xlabel('Groups')\n","ax1.set_ylabel('Proportion', color='steelblue')\n","ax2.set_ylabel('Cumulative Proportion', color='k')\n","ax2.legend(loc='center right')\n","plt.title('Pareto Chart — Anime Completions by Group')\n","plt.tight_layout()\n","plt.show()"],"id":"hw3-20"},{"cell_type":"markdown","metadata":{"id":"hw3-21"},"source":["## 4. How to Submit Your Answer to Omnicampus\n"],"id":"hw3-21"},{"cell_type":"markdown","metadata":{"id":"hw3-22"},"source":["### Step 1: Copy the complete `homework()` function\n","\n","Copy from the line beginning with `def homework(...):` through\n","the final `return` line. Copy the **function itself**, not only its body.\n","\n","Do not copy import cells, data-download cells, the test-case cells that call\n","`homework()`, the final checklist, or any printed output.\n"],"id":"hw3-22"},{"cell_type":"markdown","metadata":{"id":"hw3-23"},"source":["### Step 2: Paste it into Omnicampus and submit\n","\n","Open this homework in Omnicampus, paste the complete function\n","into the answer field, and click the submit button.\n","\n","> **🔁 You can submit as many times as you need.**\n",">\n","> If your result is `0.0`, revise your `homework()` function and submit it\n","> again. You do not have to stop after your first submission.\n","\n","The submitted function must not contain library imports. The required\n","libraries are provided by the grader.\n"],"id":"hw3-23"},{"cell_type":"markdown","source":[""],"metadata":{"id":"6Zwq5KunrRBc"},"id":"6Zwq5KunrRBc"},{"cell_type":"markdown","metadata":{"id":"hw3-24"},"source":["### Step 3: Wait for and check the grading result\n","\n","Grading may take a little time. If no result appears, wait a\n","moment and reload the browser.\n","\n","- **3.0 points** means the answer is correct.\n"," - If you submit after the deadline, **2.0 points** is the maximum you can get.\n","- **0.0 points** means the answer is not correct yet.\n","- You may revise your function and submit again.\n"],"id":"hw3-24"},{"cell_type":"markdown","source":[""],"metadata":{"id":"UUXmRH0rrSQ8"},"id":"UUXmRH0rrSQ8"},{"cell_type":"markdown","metadata":{"id":"hw3-25"},"source":[" ### Important Notes About Grading\n","\n"," 1. **Your latest submission is your final result.**\n"," Your grade is based on the most recent submission, not the highest score.\n"," For example, if you receive `3.0` and then submit another answer that receives\n"," `0.0`, your recorded result will be `0.0`.\n","\n"," 2. **Correct submissions made during the late submission period receive a maximum of 2.0 points.**\n"," Even if your answer is correct, you cannot receive `3.0` points after the\n"," original deadline.\n","\n"," 3. **The late submission window will be open to all students, including students who have already submitted.**\n"," If your latest submission already shows `3.0`, you do not need to submit\n"," again during the late submission period. Submitting again may replace your\n"," current result.\n","\n"," Before you finish, make sure your latest submission shows the score you want\n"," to keep.\n","\n"],"id":"hw3-25"},{"cell_type":"markdown","metadata":{"id":"hw3-26"},"source":["### References\n","\n","[1] Hernan4444. *MyAnimeList Database*. GitHub. https://github.com/Hernan4444/MyAnimeList-Database"],"id":"hw3-26"}],"metadata":{"kernelspec":{"display_name":"3.10.5","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.5"},"colab":{"provenance":[],"toc_visible":true},"homework_edition":"2026Sep"},"nbformat":4,"nbformat_minor":5}