{ "cells": [ { "cell_type": "markdown", "id": "6838b2de", "metadata": {}, "source": [ "# Hello" ] }, { "cell_type": "code", "execution_count": null, "id": "4200d243", "metadata": {}, "outputs": [], "source": [ "\n", "\"\"\"\n", " Use a function to get x,y position of random points in a circle\n", " and plot out the restuls with a few more new MatPlotLib features\n", "\"\"\"\n", "\n", "import random\n", "import matplotlib.pyplot as plt # Standard Matplotlib import\n", "from matplotlib.patches import Circle # Add circle from the patches module\n", "\n", "def getpoint(radius = 1.0):\n", " \"\"\"\n", " Function to get a random point in a circle of specified radius and return\n", " [x,y] as a list of floats\n", "\n", " :param radius: the circle radius (Default = 1.0)\n", " :type radius: float\n", " :return: [x,y]\n", " \"\"\"\n", " while True: # Go round loop forming x,y point\n", " x = random.uniform(-radius,radius)\n", " y = random.uniform(-radius,radius)\n", " if x*x + y*y <= radius*radius: # In in circle, sucess break out of loop\n", " break\n", "\n", " return x,y # Return the x,y point as a list\n", "\n", "\n", "def main():\n", " # Get number of points and radius of circlde\n", " npoint = int(input(\"Number of points : \"))\n", " radius = float(input(\"Radius : \"))\n", "\n", " xData = [] # Lists to hold x,y coordinates\n", " yData = []\n", "\n", " # Go round while loop getting point\n", " while npoint > 0:\n", " xpt,ypt = getpoint(radius) # use function to get point\n", " xData.append(xpt) # Add points to lists\n", " yData.append(ypt)\n", " npoint -= 1\n", "\n", "\n", " # Some more complex Matplot lib plotting (more flexible)\n", " fig,ax = plt.subplots() # Get figure and axis of default plot\n", " ax.scatter(xData,yData) # Plot points in axis as scatter plot\n", " # Add a unfilled circle at (0,0) of colour \"r\"\n", " ax.add_artist(Circle((0,0),radius,color = \"r\",fill = False))\n", " ax.axhline(y=0, color='r') # Add horizonal line though y = 0\n", " ax.axvline(x=0, color='r') # Add vertical line though x = 0\n", " ax.axis(\"equal\") # Set scale of axis to be equal in x,y\n", " plt.title(\"Scatter Plot\") # Add a ittle to the main plot\n", " plt.show() # Show the plot\n", "\n", "main()" ] } ], "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.9.7" } }, "nbformat": 4, "nbformat_minor": 5 }