{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "\n", "def show_scatter_plot(title, \n", " x_label, y_label, \n", " x_values, y_values):\n", " \"\"\"\n", " @param title the chart title.\n", " @param x_label the x-axis label.\n", " @param y_label the y-axis label.\n", " @param x_values the independent x values to plot.\n", " @param y_values the dependent y values to plot.\n", " \"\"\"\n", " plt.scatter(x_values, y_values)\n", " plt.title(title)\n", " plt.ylabel(x_label)\n", " plt.xlabel(y_label)\n", " plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import math\n", "import numpy as np\n", "\n", "def calculate_r(x_values, y_values):\n", " \"\"\"\n", " Calculate the correlation coefficient.\n", " @param x_values the x values.\n", " @param y_values the y values.\n", " @return the correlation coefficient.\n", " \"\"\"\n", " x = np.array(x_values)\n", " y = np.array(y_values)\n", " \n", " n = len(x)\n", " sum_x = np.sum(x)\n", " sum_y = np.sum(y)\n", " sum_xx = np.sum(x*x)\n", " sum_yy = np.sum(y*y)\n", " sum_xy = np.sum(x*y)\n", " \n", " numerator = sum_xy - (sum_x*sum_y)/n\n", " denominator = math.sqrt(sum_xx - (sum_x*sum_x)/n)*math.sqrt(sum_yy - (sum_y*sum_y)/n)\n", " \n", " r = numerator/denominator\n", " return r" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "xs = [ 11, 13, 18, 30, 36, 40, 50, 58, 67, 82, 91, 102]\n", "ys = [1.1, 0.5, 2.4, 1.2, 2.1, 1.2, 4.0, 2.3, 1.7, 3.7, 3.0, 3.9]\n", "\n", "show_scatter_plot('Scatter Plot', 'Dependent variable', \n", " 'Independent variable', xs, ys )" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "r = calculate_r(xs, ys)\n", "\n", "print(f'r = {r:.3f}')" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.7.7" } }, "nbformat": 4, "nbformat_minor": 4 }