{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "###
San Jose State University
Department of Applied Data Science

**DATA 200
Computational Programming for Data Analytics**

Spring 2024
Instructor: Ron Mak
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Stacked Area Chart" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Stacked area chart parameters\n", "#### To create a stacked area plot, call `plt.stackplot(x, y1, y2, y3, ...)`, where\n", "- #### *x* is the sequence of x values\n", "- #### *y1, y2, y3, ...* are sequences of y values\n", "Example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.stackplot([1, 2, 3, 4],\n", " [2, 4, 5, 8], [1, 5, 4, 2])\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Example: Smartphone Sales Units\n", "#### You want to invest in one of the biggest five smartphone manufacturers. Looking at the quarterly sales units as part of a whole may be a good indicator to invest in one of the companies. Therefore, compare smartphone sales units using a stacked area chart." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sales = pd.read_csv('smartphone_sales.csv')\n", "sales" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create the figure.\n", "plt.figure(figsize=(10, 6), dpi=300)\n", "\n", "# Create the stacked area chart.\n", "labels = sales.columns[1:]\n", "plt.stackplot('Quarter', 'Apple', 'Samsung', 'Huawei', 'Xiaomi', 'OPPO', \n", " data=sales, labels=labels)\n", "\n", "# Add the labels.\n", "plt.xlabel('Quarters')\n", "plt.ylabel('Sales units in thousands')\n", "\n", "plt.title('Smartphone sales units')\n", "plt.legend()\n", "\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Adapted from ***Data Visualization with Python***, by Mario Döbler and Tim Großmann, Packt 2019, ISBN 978-1-78995-646-7" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Additional material (c) 2024 by Ronald Mak" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.11.5" } }, "nbformat": 4, "nbformat_minor": 4 }