First commit from local

pull/3/head
Tim Skov Jacobsen 2019-09-03 11:44:13 +02:00
parent 1148ccdb68
commit f75190733c
205 changed files with 28470 additions and 0 deletions

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,396 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Session 2 - Exercise solutions\n",
"There are often many ways to do the same thing, so these are just one way of solving the problems. \n",
"\n",
"## Exercise 1"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"First element of L1 is 10 and last elements of L1 is 60\n"
]
}
],
"source": [
"L1 = [10, 20, 30, 40, 50, 60]\n",
"first_elem = L1[0]\n",
"last_elem = L1[-1]\n",
"print(f'First element of L1 is {first_elem} and last elements of L1 is {last_elem}')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 2"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[20, 30, 40]\n"
]
}
],
"source": [
"L1_sliced = L1[1:4]\n",
"print(L1_sliced)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 3"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Hey', 'Hello', 'Hi', 'Hi!', 'hey']\n"
]
}
],
"source": [
"L2 = ['Hi', 'Hello', 'Hi!', 'Hey', 'Hi', 'hey', 'Hey']\n",
"L2_unique = list(set(L2))\n",
"print(L2_unique)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 4"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"122\n"
]
}
],
"source": [
"d = {2: 122, 3: 535, 't': 'T', 'rom': 'cola'}\n",
"print(d[2]) # Print value corresponding to key 2"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"T\n"
]
}
],
"source": [
"print(d['t']) # Print value corresponding to key 't'"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I like rom and cola, but mostly the rom\n"
]
}
],
"source": [
"print(f\"I like rom and {d['rom']}, but mostly the rom\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 5"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"23 squared is 529\n",
"73 squared is 5329\n",
"12 squared is 144\n",
"84 squared is 7056\n"
]
}
],
"source": [
"n = [23, 73, 12, 84]\n",
"\n",
"# By using conventional for loop\n",
"for elem in n:\n",
" print(f'{elem} squared is {elem**2}')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 6"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[78.64750000000001, 113.25240000000001, 201.3376, 314.59000000000003, 491.546875, 805.3504]\n"
]
}
],
"source": [
"diameters = [10, 12, 16, 20, 25, 32]\n",
"areas = [3.1459 * dia**2 / 4 for dia in diameters] # To use pi the math module would need to be imported\n",
"print(areas)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['79', '113', '201', '315', '492', '805']\n"
]
}
],
"source": [
"# Convert elements to strings and round down\n",
"print([f'{area:.0f}' for area in areas])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 7"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Alpha', 'Bravo', 'Delta']\n"
]
}
],
"source": [
"phonetic_alphabet = ['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot']\n",
"words_of_5_chars = [word for word in phonetic_alphabet if len(word) == 5]\n",
"print(words_of_5_chars)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 8"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'HE200A', 'HE210B', 'HE210A'}\n"
]
}
],
"source": [
"s1 = {'HE170B', 'HE210B', 'HE190A', 'HE200A', 'HE210A', 'HE210A'}\n",
"s2 = {'HE200A', 'HE210A', 'HE240A', 'HE200A', 'HE210B', 'HE340A'}\n",
"s_intersection = s1.intersection(s2)\n",
"print(s_intersection)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 9"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[125, 435, 362, 156, 80, 435, 435]\n"
]
}
],
"source": [
"rebar_stresses = (125, 501, 362, 156, 80, 475, 489)\n",
"fy = 435\n",
"sigma_s = [stress if stress <= 435 else fy for stress in rebar_stresses]\n",
"print(sigma_s)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 10"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[-18, -25, 0, -21, -15, 0]\n"
]
}
],
"source": [
"T1 = (-18, -27, 2, -21, -15, 5)\n",
"\n",
"T2 = []\n",
"for val in T1:\n",
" if val > 0:\n",
" T2.append(0)\n",
" elif 0 > val > -25:\n",
" T2.append(val)\n",
" else:\n",
" T2.append(-25)\n",
"\n",
"print(T2)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[-18, -25, 0, -21, -15, 0]\n"
]
}
],
"source": [
"# Alternative by list comprehension with chained if's\n",
"T3 = [0 if val > 0 else val if 0 > val > -25 else -25 for val in T1]\n",
"print(T3)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"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.1"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 2
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,507 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"cell_style": "center"
},
"source": [
"\n",
"# Session 3\n",
"\n",
"\n",
"# Functions\n",
"A ***function*** is a block of code that is first defined, and thereafter can be called to run as many times as needed. A function might have arguments, some of which can be optional if a default value is specified.\n",
"A function is called by parantheses: `function_name()`. Arguments are placed inside the paranthes and comma separated if there are more than one.\n",
"Similar to `f(x, y)` from mathematics.\n",
"\n",
"A function can return one or more values to the caller. The values to return are put in the `return` statement, which ends the function. If no `return` statement is given, the function will return `None`.\n",
"\n",
"The general syntax of a function is:\n",
"\n",
"~~~python\n",
"def function_name(arg1, arg2, default_arg1=0, default_arg2=None):\n",
" '''This is the docstring \n",
" \n",
" The docstring explains what the function does, so it is like a multi line comment. It does have to be here, \n",
" but it is good practice to use them to document the code. They are especially useful for more complicated \n",
" functions.\n",
" Arguments could be explained togehter with their types (e.g. strings, lists, dicts etc.).\n",
" '''\n",
" \n",
" # Function code goes here\n",
" \n",
" # Possible 'return' statement terminating the function. If 'return' is not specified, function returns None.\n",
" return return_val1, return_val2\n",
"~~~\n",
"\n",
"If multiple values are to be returned, they can be separeted by commas. The returned entity will by default be a tuple.\n",
"\n",
"Note that when using default arguments, it is good practice to only use immutable types as defaults. An example further below will demonstrate why this is recmommended. \n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Basic functions\n",
"A simple function with one argument is defined below."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"def f(x):\n",
" return 6.25 + x + x**2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Note:** No code has been executed yet. It has merely been defined and ready to run when called.\n",
"\n",
"Calling the function with an argument returns:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"36.25\n"
]
}
],
"source": [
"print(f(5))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we define a function without returning anything, it returns `None`:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"def first_char(word):\n",
" word[0] # <--- No return statment, function returns None\n",
" \n",
"\n",
"a = first_char('hello') # Variable a will be equal to None\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Often a return value is wanted from a function, but there could be scenarios where it is not wanted. E.g. if you want to mutate a list by the function. Consider this example:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Anders\n",
"None\n"
]
}
],
"source": [
"def say_hello_to(name):\n",
" ''' Say hello to the input name '''\n",
" print(f'Hello {name}')\n",
" \n",
"\n",
"say_hello_to('Anders') # <--- Calling the function prints 'Hello {name}'\n",
"r = say_hello_to('Anders')\n",
"print(r) # <--- Prints None, since function does not return anyhing "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The function was still useful even though it did not return anything. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Local vs. global variables\n",
"\n",
"* ***Global variables***: Variables defined outside a function\n",
"* ***Local variables***: Varaiables defined inside a function\n",
"\n",
"*Local variables* cannot be accessed outside the function. By returning a *local variable* and saving it into a *global variable* we can use the result outside the function, in the global namespace."
]
},
{
"cell_type": "markdown",
"metadata": {
"cell_style": "center"
},
"source": [
"# The `enumerate` function \n",
"The `enumerate` function is useful whenever you want to loop over an iterable together with the index of each value:"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 a\n",
"1 b\n",
"2 c\n",
"3 d\n",
"4 c\n"
]
}
],
"source": [
"letters = ['a', 'b', 'c', 'd', 'c']\n",
"for idx, letter in enumerate(letters):\n",
" print(idx, letter)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 a\n",
"2 b\n",
"3 c\n",
"4 d\n",
"5 c\n"
]
}
],
"source": [
"for idx, letter in enumerate(letters, start=1): # Starting at 1 (internally, enumerate has start=0 set as default)\n",
" print(idx, letter)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# The `zip` function\n",
"The `zip`function is useful when you want to put two lists up beside eachother and loop over them."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10 78.5\n",
"12 113.04\n",
"16 200.96\n",
"20 314.0\n",
"25 490.625\n"
]
}
],
"source": [
"diameters = [10, 12, 16, 20, 25] \n",
"areas = [3.14 * (d/2)**2 for d in diameters]\n",
"\n",
"for d, A in zip(diameters, areas):\n",
" print(d, A)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Imports\n",
"\n",
"## Libraries\n",
"A quick overview of imports of libraries in Python, here shown for the math library:\n",
"\n",
"~~~python\n",
"import math # Let's you access everything in the math library by dot-notation (e.g math.pi) \n",
"from math import pi # Let's you use pi directly\n",
"from math import * # Let's you use everything in the math library directly \n",
"~~~\n",
"The last one is not considered good practice, since varaibles will be untracable. It can be good for making quick tests though.\n",
"\n",
"## Your own modules\n",
"You can also import your own *.py* files this way and access the functions inside them. It is easiest if the file to import is located in the same folder as the *.py* file you want to import to. Note that Python files *.py* are normally called ***modules***.\n",
"\n",
"An example:\n",
"\n",
"~~~python\n",
"import my_module # my_module could be your own python file located in same directory\n",
"~~~\n",
"If you have a function inside `my_module` called `my_func`, you can now call it as `my_module.my_func()`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 1\n",
"Finish the function below that takes a radius as input and make it return the circle area.\n",
"\n",
"~~~python\n",
"def circle_area(r):\n",
" '''Return circle area'''\n",
" # Your code goes here\n",
"~~~\n",
"\n",
"Try to call it to see if it works. If you wan to access `pi` to avoid typing it out yourself, put the line `from math import pi` at some point before calling the function.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 2\n",
"Write a function that takes a list `radii` as input and returns a list of the corresponding circle areas. Try to set it up from scrath and test it.\n",
"\n",
"You can use the function from the previous exercise if you want."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 3\n",
"Write the function described in the docstring below.\n",
"\n",
"~~~Python\n",
"def is_pile_long(pile_lengths):\n",
" ''' Return a list with elements `True` for all piles longer than or equal to 5m, `False` otherwise.\n",
" \n",
" Args:\n",
" pile_length : A list containing pile lengths \n",
" \n",
" Example: \n",
" is_pile_long([4.51, 6.12, 4.15, 7.31, 5.01, 4.99, 5.00])\n",
" ---> [False, True, False, True, True, False, True] \n",
" '''\n",
" # Your code goes here\n",
" \n",
"~~~"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 4\n",
"Finish the function below so it does as described in the docstring. Remember to import the `sqrt` function from the math module.\n",
"\n",
"---\n",
"~~~python\n",
"def dist_point_to_line(x, y, x1, y1, x2, y2):\n",
" '''Return distance between a point and a line defined by two points.\n",
" \n",
" Args:\n",
" x : x-coordinate of point \n",
" y : y-coordinate of point\n",
" x1 : x-coordinate of point 1 defining the line\n",
" y1 : y-coordinate of point 1 defining the line\n",
" x2 : x-coordinate of point 2 defining the line\n",
" y2 : y-coordinate of point 2 defining the line\n",
" \n",
" Returns:\n",
" The distance between the point and the line \n",
" '''\n",
" # Your code goes here\n",
"~~~\n",
"---\n",
"The distance between a point $(x, y)$ and a line passing through points $(x_1, y_1)$ and $(x_2, y_2)$ can be found as\n",
"\n",
"\\begin{equation*}\n",
"\\textrm{ distance}(P_1, P_2, (x, y)) = \\frac{|(y_2-y_1)x - (x_2-x_1)y + x_2 y_1 - y_2 x_1|}{\\sqrt{ (x_2-x_1)^2 + (y_2-y_1)^2 }}\n",
"\\end{equation*}\n",
"\n",
"Call the function to test if it works. Some examples to test against:\n",
"\n",
"~~~python\n",
"dist_point_to_line(2, 1, 5, 5, 1, 6) --> 4.61 \n",
"dist_point_to_line(1.4, 5.2, 10.1, 2.24, 34.142, 13.51) --> 6.37 \n",
"~~~\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 5\n",
"Given a line defined by points $(x_1, y_1)=(2, 3)$ and $(x_2, y_2)=(8, 7)$, compute the distance to the points with the coordinates below and put the results into a list\n",
"\n",
"~~~python\n",
"x_coords = [4.1, 22.2, 7.7, 62.2, 7.8, 1.1]\n",
"y_coords = [0.3, 51.2, 3.5, 12.6, 2.7, 9.8]\n",
"~~~\n",
"\n",
"You can either use a list comprehension or create a traditional `for` loop where results get appended to the list in every loop.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 6\n",
"Create a function that calculates the area of a simple (non-self-intersecting) polygon by using the so-called *Shoelace Formula*\n",
"\n",
"$$ A_p = \\frac{1}{2} \\sum_{i=0}^{n-1} (x_i y_{i+1} - x_{i+1} y_i) $$\n",
"\n",
"The area is *signed* depending on the ordering of the polygon being clockwise or counter-clockwise. The numerical value of the formula will always be equal to the actual area.\n",
"\n",
"The function should take three input parameters:\n",
"\n",
"* `xv` - list of x-coordinates of all vertices\n",
"* `yv` - list of y-coordinates of all vertices\n",
"* `signed` - boolean value that dictates whether the function returns the signed area or the actual area. Default should be actual area.\n",
"\n",
"Assume that the polygon is closed, i.e. the first and last elements of `xv` are identical and the same is true for `yv`.\n",
"\n",
"A function call with these input coordinates should return `12.0`: \n",
"~~~python \n",
"x = [3, 4, 7, 8, 8.5, 3]\n",
"y = [5, 3, 0, 1, 3, 5]\n",
"~~~\n",
"\n",
"Source: https://en.wikipedia.org/wiki/Polygon#Area"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise 7\n",
"Write a function that calculates and returns the centroid $(C_x, C_y)$ of a polygon by using the formula:\n",
"\n",
"$$ C_x = \\frac{1}{6A} \\sum_{i=0}^{n-1} (x_i+x_{i+1}) (x_i y_{i+1} - x_{i+1} y_i) $$\n",
"\n",
"$$ C_y = \\frac{1}{6A} \\sum_{i=0}^{n-1} (y_i+y_{i+1}) (x_i y_{i+1} - x_{i+1} y_i) $$\n",
"\n",
"`x` and `y` are lists of coordinates of a closed simple polygon.\n",
"\n",
"Here, $A$ is the *signed* area. When you need $A$, call the function from the previous exercise to get it. Be sure to call it with the non-default `signed=True`. \n",
"\n",
"A function call with the input coordinates below should return (`6.083`, `2.583`):\n",
"~~~python\n",
"x = [3, 4, 7, 8, 8.5, 3]\n",
"y = [5, 3, 0, 1, 3, 5]\n",
"~~~\n",
"\n",
"Source: https://en.wikipedia.org/wiki/Centroid#Of_a_polygon"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## If you are up for more\n",
"Try to write a function that can calculate the elastic centroid of a section with materials of two different stiffness values. E.g. a reinforced concrete section with polygon shape."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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.1"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
"autoclose": false,
"autocomplete": true,
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1,
"eqLabelWithNumbers": true,
"eqNumInitial": 1,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
},
"labels_anchors": false,
"latex_user_defs": false,
"report_style_numbering": false,
"user_envs_cfg": false
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": false,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": true
}
},
"nbformat": 4,
"nbformat_minor": 2
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,125 @@
# Compute distance from point (2, 5) to point (3, 4)
x1, y1, x2, y2 = 2, 5, 3, 4
dist1 = ((x2 - x1)**2 + (y2 - y1)**2)**(0.5)
# Compute distance from point (7, 6) to point (3, 5)
x1, y1, x2, y2 = 7, 6, 3, 5
dist2 = ((x2 - x1)**2 + (y2 - y1)**2)**(0.5)
# Compute distance from point (2, 4) to point (7, 5)
x1, y1, x2, y2 = 2, 4, 7, 5
dist3 = ((x2 - x1)**2 + (y2 - y1)**2)**(0.5)
# Same lines are repeated many times ==> Hard to maintain or change ==> create a function
# ------------------------------------------------
# Same code as above:
def points_dist(x1, y1, x2, y2):
'''Compute the distance between two points (x1, y1) and (x2, y2)'''
return ((x2 - x1)**2 + (y2 - y1)**2)**(0.5)
# Calculate the distances by function calls
dist1 = points_dist(2, 5, 3, 4)
dist2 = points_dist(7, 6, 3, 5)
dist3 = points_dist(2, 4, 7, 5)
# -----------------------------------------------
# Alternative by function and list comprehension
xx1 = [2, 7, 2]
yy1 = [5, 6, 4]
xx2 = [3, 3, 7]
yy2 = [4, 5, 5]
distances = [points_dist(xx1[i], yy1[i], xx2[i], yy2[i]) for i in range(len(xx1))]
print(distances)
# -----------------------------------------------
# Alternative with list comprehension and zip
distances2 = [points_dist(x1, y1, x2, y2) for i in zip(xx1, yy1, xx2, yy2)]
print(distances)
def polygon_area(xv, yv, signed=False):
''' Return the area of a non-self-intersecting polygon given the coordinates of its vertices'''
# Perform shoelace multiplication
a1 = [xv[i] * yv[i+1] for i in range(len(xv)-1)]
a2 = [yv[i] * xv[i+1] for i in range(len(yv)-1)]
# Check is area should be signed and return area
if signed: # <--- Same as "if signed == True:"
return 1/2 * ( sum(a1) - sum(a2) )
else:
return 1/2 * abs( sum(a1) - sum(a2) )
def polygon_centroid(x, y):
# Initialize empty lists for holding summation terms
cx, cy = [], []
# Loop over vertices and put the summation terms in the lists
for i in range(len(x)-1):
# Compute and append summation terms to each list
cx.append((x[i] + x[i+1]) * (x[i] * y[i+1] - x[i+1] * y[i]))
cy.append((y[i] + y[i+1]) * (x[i] * y[i+1] - x[i+1] * y[i]))
# Calculate the signed polygon area by calling already defined function
A = polygon_area(x, y, signed=True)
# Sum summation terms and divide by 6A to get coordinates
Cx = sum(cx) / (6*A)
Cy = sum(cy) / (6*A)
return Cx, Cy
def plot_polygon(xv, yv, plot_centroid=True):
'''Plot the polygon with the specified vertex coordinates.
The plot is created with legend and the computed area of the
polygon shown in the title. The plots shows the centroid of
the polygon, but this can be turned off by setting
plot_centroid=False.
Args:
xv (list) : x-coordinates of polygon vertices
yv (list) : y-coordinates of polygon vertices
plot_centroid (bool) : Plot centroid of polygon (Cx, Cy).
Defaults to plotting the centroid.
'''
# Compute area of polygon
A = polygon_area(xv, yv)
# Compute polygon centroid
cx, cy = polygon_centroid(xv, yv)
# Plot the polygon
plt.plot(xv, yv, '.-', label='Polygon')
# Plot the centroid with coordinates if that was chosen
if plot_centroid: # <- Eqiuvalent to: if plot_centroid == True:
plt.plot(cx, cy, 'x', label='Centroid')
plt.annotate(f'({cx:.1f}, {cy:.1f})', xy=(cx, cy),
xytext=(cx, cy), textcoords='offset points')
# Set labels, titles and legend
plt.xlabel('x')
plt.ylabel('y')
plt.title(f'Polygon with A={A}')
plt.legend()
plt.show()
import matplotlib.pyplot as plt
x_polygon = [-5, 2, 5, 7, 8, 5, 1, -5]
y_polygon = [-2, -15, -13, -10, -6, 2, 5, -2]
plot_polygon(x_polygon, y_polygon)

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

View File

@ -0,0 +1,688 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"toc": true
},
"source": [
"<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n",
"<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Session-4\" data-toc-modified-id=\"Session-4-1\">Session 4</a></span></li><li><span><a href=\"#Plotting-with-matplotlib\" data-toc-modified-id=\"Plotting-with-matplotlib-2\">Plotting with <code>matplotlib</code></a></span><ul class=\"toc-item\"><li><span><a href=\"#Simple-plotting-API\" data-toc-modified-id=\"Simple-plotting-API-2.1\">Simple plotting API</a></span><ul class=\"toc-item\"><li><span><a href=\"#Customization-of-graphs\" data-toc-modified-id=\"Customization-of-graphs-2.1.1\">Customization of graphs</a></span></li><li><span><a href=\"#Plotting-multiple-graphs-in-the-same-plot\" data-toc-modified-id=\"Plotting-multiple-graphs-in-the-same-plot-2.1.2\">Plotting multiple graphs in the same plot</a></span></li><li><span><a href=\"#Fill-between\" data-toc-modified-id=\"Fill-between-2.1.3\">Fill between</a></span></li><li><span><a href=\"#Subplots\" data-toc-modified-id=\"Subplots-2.1.4\">Subplots</a></span></li></ul></li><li><span><a href=\"#Object-Oriented-API\" data-toc-modified-id=\"Object-Oriented-API-2.2\">Object Oriented API</a></span><ul class=\"toc-item\"><li><span><a href=\"#Subplots\" data-toc-modified-id=\"Subplots-2.2.1\">Subplots</a></span></li></ul></li><li><span><a href=\"#Online-help-and-plotting-galleries\" data-toc-modified-id=\"Online-help-and-plotting-galleries-2.3\">Online help and plotting galleries</a></span></li></ul></li><li><span><a href=\"#Numerical-computation-library:-numpy\" data-toc-modified-id=\"Numerical-computation-library:-numpy-3\">Numerical computation library: <code>numpy</code></a></span></li><li><span><a href=\"#Exercises\" data-toc-modified-id=\"Exercises-4\">Exercises</a></span><ul class=\"toc-item\"><li><span><a href=\"#Exercise-1.1\" data-toc-modified-id=\"Exercise-1.1-4.1\">Exercise 1.1</a></span></li><li><span><a href=\"#Exercise-1.2\" data-toc-modified-id=\"Exercise-1.2-4.2\">Exercise 1.2</a></span></li><li><span><a href=\"#Exercise-1.3\" data-toc-modified-id=\"Exercise-1.3-4.3\">Exercise 1.3</a></span></li><li><span><a href=\"#Exercise-1.4\" data-toc-modified-id=\"Exercise-1.4-4.4\">Exercise 1.4</a></span></li><li><span><a href=\"#Exercise-1.5\" data-toc-modified-id=\"Exercise-1.5-4.5\">Exercise 1.5</a></span></li><li><span><a href=\"#Exercise-1.6\" data-toc-modified-id=\"Exercise-1.6-4.6\">Exercise 1.6</a></span></li><li><span><a href=\"#Exercise-2.1\" data-toc-modified-id=\"Exercise-2.1-4.7\">Exercise 2.1</a></span></li><li><span><a href=\"#Exercise-2.2\" data-toc-modified-id=\"Exercise-2.2-4.8\">Exercise 2.2</a></span></li><li><span><a href=\"#Exercise-3.1\" data-toc-modified-id=\"Exercise-3.1-4.9\">Exercise 3.1</a></span></li><li><span><a href=\"#Exercise-4.1\" data-toc-modified-id=\"Exercise-4.1-4.10\">Exercise 4.1</a></span></li><li><span><a href=\"#If-you-are-up-for-more\" data-toc-modified-id=\"If-you-are-up-for-more-4.11\">If you are up for more</a></span></li></ul></li></ul></div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Session 4\n",
"\n",
"# Plotting with `matplotlib`\n",
"There are many plotting libraries in the Python ecosystem, and more being added all the time. The most widely known is called `matplotlib`, which is the one we are going to focus on.\n",
"\n",
"`matplotlib` is a third party library, which means that it is developed and maintained by the Python Community and not the core developers of the Python language itself. This means that it doesn't ship with the Python installation and has to be installed separately before we can import it and use it in our programs. `matplotlib` is one of the oldest, most known and well documented third party libraries in Python.\n",
"\n",
"To install the library, go to the Windows start menu and find *Anaconda Prompt*. When it opens, type `pip install matplotlib` and hit enter. This should install the most recent version on your system."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cell_style": "center"
},
"outputs": [],
"source": [
"# Enable for plots to be shown inside Jupyter Notebook cells \n",
"# (Note: This line is not needed when using an editor) \n",
"%matplotlib inline \n",
"\n",
"# The lines below sets the figure size throughout the notebook\n",
"import matplotlib as mpl\n",
"mpl.rcParams['figure.figsize'] = 7, 5"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Import the plotting library and refer to it as plt later on\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is customary to import `as plt` so referencing can be done as \n",
"\n",
"~~~python\n",
"plt.do_something() # plt replaces matplotlib.pyplot\n",
"~~~\n",
"Where `do_something()` is some function/method inside `matplotlib`. This is much shorter than typing\n",
"~~~python\n",
"matplotlib.pyplot.do_something() # Long and cumbersome to type\n",
"~~~\n",
"\n",
"In fact, the `plt` part could be named differently, but it is widely accepted to use this naming, which makes it easier to read other people's code."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Simple plotting API\n",
"The simple API for plotting in `matplotlib` uses commands which deliberately were chosen very similar to the `Matlab` syntax. \n",
"\n",
"API stand for *Application Programming Interface* and is basically a simplified way of interacting with more complex underlying code. Here, we will type fairly simple plotting commands, which do a lot of low level work in the background.\n",
"\n",
"Creating a simple line plot is extremely easy: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create x- and y-coordinates for f(x) = x^2 \n",
"x = [i for i in range(-100, 105, 5)]\n",
"y = [i**2 for i in x]\n",
"\n",
"# Create basic plot\n",
"plt.plot(x, y)\n",
"\n",
"# Show plot\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Given a list of data for `x` and `y`, a line graph can be produced in a single command `plt.plot(x,y)`, while actually showing the plot has its own command. \n",
"\n",
"It might seem wierd that the `plt.show()` is needed, but it is not always desired to have the plot shown. Sometimes it is desired to produce the graph and have it saved to a png-file or do something else with it instead of showing it. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Customization of graphs\n",
"The plot of $f(x)=x^2$ from above can be made much nicer by a little customization. The command names should make the code self-explanatory."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.title('Graph for $f(x) = x^2$', fontsize=16)\n",
"plt.xlabel('$x$', fontsize=14)\n",
"plt.ylabel('$f(x)$', fontsize=14)\n",
"plt.plot(x, y, '.-', color='limegreen', markersize=6)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Plotting multiple graphs in the same plot\n",
"It is possible to plot many graphs in the same plot and attach a legend:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create x-coordinates for graphs \n",
"x = [i for i in range(-10, 10, 1)]\n",
"\n",
"# Produce y-values for different graphs\n",
"y1 = [i**2 for i in x] # f(x) = x^2\n",
"y2 = [10*i**2 for i in x] # f(x) = 10x^2\n",
"y3 = [i**3 for i in x] # f(x) = x^3\n",
"y4 = [2*i**3 for i in x] # f(x) = 2x^3\n",
"\n",
"# Create plots with legend labels for each graph\n",
"plt.plot(x, y1, label='$f(x)=x^2$')\n",
"plt.plot(x, y2, label='$f(x)=10x^2$')\n",
"plt.plot(x, y3, label='$f(x)=x^3$')\n",
"plt.plot(x, y4, label='$f(x)=2x^3$')\n",
"\n",
"# Set titles, grid and legend\n",
"plt.title('Different graphs', fontsize=16)\n",
"plt.xlabel('$x$', fontsize=14)\n",
"plt.ylabel('$y$', fontsize=14)\n",
"plt.grid(linestyle=':')\n",
"plt.legend(fontsize=14)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Graphs are automatically colorized, but this can of course be customized.\n",
"* Legend will try to position itself so it does not overlap with the graphs. \n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Fill between\n",
"Plot areas can be filled based on conditions. Below is an example.\n",
"\n",
"The code in the next cell serves only to create summy data for a graph. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The code in this cell is just for creating a dummy graph\n",
"import numpy as np\n",
"x1 = np.linspace(1, 10, 100)\n",
"x2 = np.linspace(10, 15, 100)\n",
"x3 = np.linspace(15, 20, 100)\n",
"y1 = 2 * np.sin(1.98*x1)\n",
"y2 = 3 * np.sin(-x2)\n",
"y3 = 1 * np.sin(2.2 * x3)\n",
"y = np.append(np.append(y1, y2), y3)\n",
"x = np.append(np.append(x1, x2), x3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Plotting this dummy graph and filling areas between the graph and $y=0$ with green color:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Plot line graph in black\n",
"plt.plot(x, y, color='black', linewidth=1)\n",
"\n",
"# Put green/purple fill between the graph y=0\n",
"plt.fill_between(x, y, color='limegreen', alpha=.25)\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"With differentiated colors:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Plot line graph in black\n",
"plt.plot(x, y, color='black', linewidth=1)\n",
"\n",
"# Put green/purple fill between the graph y=0\n",
"plt.fill_between(x, y, where= y <= 0, color='limegreen', alpha=.25)\n",
"plt.fill_between(x, y, where= y > 0, color='darkorchid', alpha=.25)\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" * **Note:** The sequences to be plotted has to be numpy arrays in order to make element wise comparison like `where= y > 0`. Trying this with standard Python lists will throw a `TypeError: '<' not supported between instances of 'list' and 'int'`. This is one of the many benefits of `numpy`. See a little more info about `numpy` later in this text."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Subplots\n",
"Creating subplots is also straight forward:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create a figure for holding subplots and set size\n",
"plt.figure(figsize=(14,3))\n",
"\n",
"# Create first plot as line plot\n",
"plt.subplot(131)\n",
"plt.plot([1, 2, 3, 4], [1, 2, 3, 4])\n",
"\n",
"# Create second plot as scatter plot\n",
"plt.subplot(132)\n",
"plt.plot([1, 2, 3, 4], [1, 2, 3, 4], '.', markersize=12)\n",
"\n",
"# Create third plot as bar plot\n",
"plt.subplot(133)\n",
"plt.bar([1, 2, 3, 4], [1, 2, 3, 4])\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* **Note 1:** The `subplot` argument conatins three digits, where the first one is the number of rows, the second the number of columns and the third the current plot to manipulate. \n",
"\n",
"\n",
"* **Note 2:** For making more complicated grid formations, shared axis tick marks etc. The *Object Oriented API* should be used instead."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Object Oriented API\n",
"Almost every aspect of a visualization can be controlled. However, in order to access more complex controls, the way of interaction with the graph elements also becomes a little more complex. \n",
"\n",
"In order to use the more powerful `matplotlib` API, we get into so-called *Object Oriented Programming*. We access each element of a figure as an *object* and manipulate that object.\n",
"\n",
"The figure below gives an overview of the objects that can be controlled."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The purpose of the code below is to show the image \n",
"from IPython.display import Image\n",
"Image(filename=\"matplotlib_objects.png\", width=600, height=600)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Subplots"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Note especially that the `Axes` object is the actual content of the plot, and therefore does not refer to *x*- or *y*-axis themselves.\n",
"\n",
"The Object Oriented API is recommended for more complex plotting like creation of larger grids of subplots where each plot needs independent adjustments. For example: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create a 2 by 3 subplot grid with shared x- and y-axis\n",
"fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')\n",
"\n",
"# Put content on the plot at grid spot 1,1 (0 indexed)\n",
"ax[1, 1].plot([1, 2, 3], [1 ,2, 3], 'g-.')\n",
"ax[1, 1].plot([3, 2, 1], [1, 2, 3], 'm:')\n",
"\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* In this manner, all objects on every subplot can manipulated.\n",
"\n",
"* There are many other plot types where the *Object Orientated API* is preferred compared to the simple Matlab style one."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Online help and plotting galleries\n",
"Instead of creating a figure from scrath, it can be quicker to serch the web for the graph style of choice, fetch a piece of code and modify it. \n",
"\n",
"Here are some useful links:\n",
"\n",
"* Plotting gallery for `matplotlib` with code examples: https://matplotlib.org/gallery/index.html\n",
"\n",
"\n",
"* Some more examples with `matplotlib`: https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/\n",
"\n",
"\n",
"* Predefined styles `matplotlib`: https://matplotlib.org/gallery/style_sheets/style_sheets_reference.html\n",
"\n",
"\n",
"* Predefined colors for `matplotlib`: https://matplotlib.org/gallery/color/named_colors.html. Colors can also be defined as hexidecimal or RGB.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Numerical computation library: `numpy`\n",
"Another very well known and broadly used third party library is `numpy` (short for Numerical Python), which contains many useful features for fast and efficient numerical calculations. This library has a lot of the same functionality as `Matlab` and utilizes vectorization to perform calculations.\n",
"\n",
"It can be installed in the same way as every other third party library, namely by entering `pip install numpy` in the *Anaconda Prompt*.\n",
"\n",
"Once installed, the `numpy` can be used as shown below. Like with the `matplotlib` import, `numpy`also has a community accepted standard:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The basic data structure in `numpy` is called an array, which can be compared to a normal Python list, except it can only hold numerical values. \n",
"\n",
"A numpy array can be created, for example from a list, like this:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"L = [1, 2, 3, 4, 5] # A normal Python list\n",
"arr = np.array(L) # List converted to numpy array"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Printing the array looks like a normal list:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(arr) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"But it is in fact a `numpy` array, which can be seen by inspecting the type:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(type(arr))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The fact that `numpy` uses verctorization can be seen for example by performing mulitplication:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Multiply all array elements by 2 and print result\n",
"arr_double = 2 * arr\n",
"print(arr_double)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Recall that doing the same operation with a normal Python list is a little more complicated. Here shown with a list comprehension, but a normal `for` loop could also be used. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Multiply all list elements by 2 and print result\n",
"L_double = [2*i for i in L]\n",
"print(L_double)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As mentioned, `numpy` has many useful functions and methods. One of the most used functions is \n",
"\n",
"~~~python\n",
"numpy.linspace(start, stop, num=50) \n",
"~~~\n",
"which will generate an array of `num` numbers evenly spaced between `start` and `end`. As we day from Session 3 about functions, the `num=50` means that `num` is an optional argument, the default value of which is 50. So, if `num` is not specified, the generated array will have 50 evenly spaced numbers between `start`and `end`.\n",
"\n",
"**Note** that the `numpy.linspace()` function has more arguments, which are not shown here. See the documention for more info: https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html\n",
"\n",
"An example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.linspace(0, 1, 10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `numpy.linspace()` function can especially be useful when generating $x$-values for plotting purposes."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Exercises\n",
"\n",
"All exercises use the simple API described above.\n",
"\n",
"## Exercise 1.1\n",
"\n",
"Plot a black line graph with dots at the points with these coordinates:\n",
"\n",
"~~~python\n",
"x = [1, 3, 6, 9, 16]\n",
"y = [7, 3, 7, 1, 5]\n",
"~~~\n",
"\n",
"Remember to `import matplotlib.pyplot as plt` and to call `plt.show()`. \n",
"\n",
"The color can be set by `plt.plot(..., color='black')` or by a shortcut `plt.plot(..., 'k')`, where `'k'` is black becuase `'b'` is blue. \n",
"\n",
"## Exercise 1.2\n",
"Set the plot title on the graph from Exercise 1.1. You choose what the title should be.\n",
"\n",
"## Exercise 1.3\n",
"Set the title of the *x-* and *y*-axis on the graph from Exercise 1.1. You choose what the title should be.\n",
"\n",
"## Exercise 1.4\n",
"Add the graphs with the following *y-*values to the plot from Exercise 1.1. Use the same *x-*values for all curves.\n",
"\n",
"~~~python\n",
"y2 = [9, 5, 5, 2, 6]\n",
"y3 = [4, 6, 2, 6, 8]\n",
"y4 = [1, 8, 1, 3, 2]\n",
"~~~\n",
"\n",
"## Exercise 1.5\n",
"Go back through the code from the previous exercises and add a `label` to the plots that were procuded. Choose a label text freely.\n",
"Afterwards, add a lenged to the plot. \n",
"\n",
"## Exercise 1.6 \n",
"Save the figure to a png-file. This can be done by the command `plt.savefig(desired_filename.png)`. This will save it in the same folder as you have your script.\n",
"\n",
"\n",
"*If you are dissatisfied with the size of the saved figure, this can be adjusted by explicitly creating the figure object before any of the graphs are created. Creating the figure object and setting a size is done by `plt.figure(figsize=(width, height))`. Both `width` and `height` are in inches. Try with different values.*\n",
"\n",
"\n",
"*Note: When using the simple API it is not necessary to explicitly create the figure object before starting the plotting with `plt.plot()`, as the figure is automaticllay created in the background with default settings. When saving to a file where it is not possible to drag the plot after creation, it is often useful to set the figure size beforehand*\n",
"\n",
"## Exercise 2.1\n",
"Create a new figure by the command `plt.figure()`. This will create a new figure object that subsequent commands will tie to. This is to avoid having the commands in this exercise be plotted in the plot from the previous exercises. \n",
"\n",
"\n",
"Redo the graphs from the previous exercises, this time split into four subplots instead. You choose how to structure the grid and how to style the graphs with colors, titles, line types etc.\n",
"\n",
"\n",
"## Exercise 2.2\n",
"Create a new figure and replicate the same subplots as in Exercise 2.1. But this time, turn the plots into bar plots. The only difference is that the plotting call should now be `plt.bar(...)`.\n",
"\n",
"\n",
"## Exercise 3.1\n",
"Create plot that is filled with some color of your choice between $y=0$ and the curve defined by $xx$ and $yy$ below:\n",
"\n",
"~~~python \n",
"import numpy as np\n",
"xx = np.linspace(-100, 100, 100)\n",
"yy = xx**2-3027 # <- Elementwise multiplication (numpy)\n",
"~~~\n",
"\n",
"\n",
"## Exercise 4.1\n",
"Use `numpy.linspace()` to create an array with 10 values from 1-10. Save the array in a a variable called `x_arr`.\n",
"\n",
"Use the code below to create the *y*-values for five graphs. \n",
"\n",
"~~~python \n",
"y_arr1 = np.random.rand(10)\n",
"y_arr2 = np.random.rand(10)\n",
"y_arr3 = np.random.rand(10)\n",
"y_arr4 = np.random.rand(10)\n",
"y_arr5 = np.random.rand(10)\n",
"~~~\n",
"\n",
"\n",
"*The `numpy.random.rand()` function creates random values between 0 and 1 (see documentation for more: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html)*\n",
"\n",
"\n",
"Create a loop that goes through the five graphs. Each loop should create a figure with your chosen size and settings for the current graph and save it to a png-file.\n",
"You should end up with five png-files each containing only a single graph/curve."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## If you are up for more \n",
"Take the polygon plotting function `plot_polygon()` from the exercise solutions from Session 3. Create different polygons, run them through a for loop and save them to png-files. Remember that the function calls the functions `polygon_area()` and `polygon_centroid`, which also have to be copied."
]
}
],
"metadata": {
"hide_input": false,
"kernelspec": {
"display_name": "Python [default]",
"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.6.6"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
"autoclose": false,
"autocomplete": true,
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1,
"eqLabelWithNumbers": true,
"eqNumInitial": 1,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
},
"labels_anchors": false,
"latex_user_defs": false,
"report_style_numbering": false,
"user_envs_cfg": false
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": false,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Table of Contents",
"toc_cell": true,
"toc_position": {
"height": "calc(100% - 180px)",
"left": "10px",
"top": "150px",
"width": "228.509px"
},
"toc_section_display": true,
"toc_window_display": true
}
},
"nbformat": 4,
"nbformat_minor": 2
}

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

View File

@ -0,0 +1,74 @@
import matplotlib.pyplot as plt
# for i in [1, 2, 3]:
# # Create a figure for holding subplots and set size
# plt.figure(figsize=(14,3))
# # Create first plot as line plot
# plt.subplot(131)
# plt.plot([1, 2, 3, 4], [1, 2, 3, 4])
# # Create second plot as scatter plot
# plt.subplot(132)
# plt.scatter([1, 2, 3, 4], [1, 2, 3, 4])
# # Create third plot as bar plot
# plt.subplot(133)
# plt.bar([1, 2, 3, 4], [1, 2, 3, 4])
# plt.show()
# Create a 2 by 3 subplot grid with shared x-a and y-axis
# fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
# plt.show()
# plt.figure(figsize=(10,5))
# --- EXERCISE 1.1 ---
x = [1, 3, 6, 9, 16]
y = [7, 3, 7, 1, 5]
plt.plot(x, y, 'k.-', label='Original curve')
# --- EXERCISE 1.2 ---
plt.title('This is the title')
# --- EXERCISE 1.3 ---
plt.xlabel('This is the xlabel')
plt.ylabel('This is the ylabel')
# --- EXERCISE 1.4 ---
y2 = [9, 5, 5, 2, 6]
y3 = [4, 6, 2, 6, 8]
y4 = [1, 8, 1, 3, 2]
plt.plot(x, y2, label='Second curve')
plt.plot(x, y3, label='Third curve')
plt.plot(x, y4, label='Fourth curve')
# --- EXERCISE 1.5 ---
# The labels in the plot commands above were
# added as part of this exercise
plt.legend()
# plt.show()
# Create a figure for holding subplots and set size
plt.figure()
# Create first plot as line plot
plt.subplot(131)
plt.plot([1, 2, 3, 4], [1, 2, 3, 4])
# Create second plot as scatter plot
plt.subplot(132)
plt.plot([1, 2, 3, 4], [1, 2, 3, 4], '.', markersize=12)
# Create third plot as bar plot
plt.subplot(133)
plt.bar([1, 2, 3, 4], [1, 2, 3, 4])
plt.show()

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Some files were not shown because too many files have changed in this diff Show More