{"id":1801,"date":"2021-12-11T19:39:56","date_gmt":"2021-12-11T19:39:56","guid":{"rendered":"https:\/\/thepythoncodingbook.com\/?p=1801"},"modified":"2023-11-12T11:36:18","modified_gmt":"2023-11-12T11:36:18","slug":"simulating-3d-solar-system-python-matplotlib","status":"publish","type":"post","link":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/","title":{"rendered":"Simulating a 3D Solar System In Python Using Matplotlib (Orbiting Planets Series #2)"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">One of the uses of programming is to help us understand the real world through simulation. This technique is used in science, finance, and many other quantitative fields. As long as the &#8220;rules&#8221; which govern the real-world properties are known, you can write a computer program that explores the outcomes you get from following those rules. In this article, you&#8217;ll <strong>simulate a 3D solar system in Python<\/strong> using the popular visualisation library Matplotlib.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you want to start with a simpler version of this project, you can read the first article in the Orbiting Planets Series. The first article deals with <a href=\"https:\/\/thepythoncodingbook.com\/2021\/09\/29\/simulating-orbiting-planets-in-a-solar-system-using-python-orbiting-planets-series-1\/\">simulating orbiting planets<\/a> in 2D and uses the relatively simple <code>turtle<\/code> graphics module. This article is the second in the series and will define classes that are modelled on the ones used in the 2D version. However, you don&#8217;t need to have read and followed the first article. If you prefer, you can jump straight into the 3D version in this article.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By the end of this article, you&#8217;ll be able to create your own 3D solar system in Python with as many suns and planets as you wish. Here&#8217;s an example of a simple solar system with one sun and two planets:<\/p>\n\n\n\n<figure class=\"wp-block-video wp-block-embed is-type-video is-provider-videopress\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"VideoPress Video Player\" aria-label='VideoPress Video Player' width='739' height='416' src='https:\/\/videopress.com\/embed\/Wn1foYop?cover=1&amp;preloadContent=metadata&amp;hd=0' frameborder='0' allowfullscreen data-resize-to-parent=\"true\" allow='clipboard-write'><\/iframe><script src='https:\/\/v0.wordpress.com\/js\/next\/videopress-iframe.js?m=1725245713'><\/script>\n<\/div><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll also be able to turn on a 2D projection on the floor of the animation to show the 3D nature of the solar system better. Here&#8217;s the same solar system simulation, including the 2D projection:<\/p>\n\n\n\n<figure class=\"wp-block-video wp-block-embed is-type-video is-provider-videopress\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"VideoPress Video Player\" aria-label='VideoPress Video Player' width='739' height='416' src='https:\/\/videopress.com\/embed\/pwbyAqEb?cover=1&amp;preloadContent=metadata&amp;hd=0' frameborder='0' allowfullscreen data-resize-to-parent=\"true\" allow='clipboard-write'><\/iframe><script src='https:\/\/v0.wordpress.com\/js\/next\/videopress-iframe.js?m=1725245713'><\/script>\n<\/div><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"outline-of-the-article\">Outline of the article<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an outline of this article so that you know what&#8217;s coming:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A brief discussion about the <strong>gravitational attraction between two bodies <\/strong>which you&#8217;ll need to use for simulating a 3D solar system in Python.<\/li>\n\n\n\n<li>A brief introduction to <strong>vectors in 3D<\/strong>.<\/li>\n\n\n\n<li><strong>Definition of classes for the solar system and the orbiting bodies<\/strong> within it, such as suns and planets. You&#8217;ll write these classes in a step-by-step approach and test them with a simple solar system.<\/li>\n\n\n\n<li>Addition of the <strong>option to show a 2D projection<\/strong> of the orbiting bodies along with the 3D simulation. This 2D projection helps to visualise the motion in 3D.<\/li>\n\n\n\n<li>Creation of a<strong> binary star system<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll use object-oriented programming and Matplotlib in this article. If you wish to read more about either topic, you can read:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/\">Object-Oriented Programming<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/thepythoncodingbook.com\/basics-of-data-visualisation-in-python-using-matplotlib\/\">Basics of Data Visualisation in Python Using Matplotlib<\/a><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s make a start with simulating a 3D solar system in Python using Matplotlib.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"let-s-talk-about-gravity\">Let&#8217;s Talk About Gravity<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Suns, planets, and other objects in a solar system are bodies that are in motion and that attract each other due to the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Newton%27s_law_of_universal_gravitation\">gravitational force<\/a> exerted between any two objects.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If the two objects have masses <span class=\"katex-eq\" data-katex-display=\"false\">m_1<\/span> and <span class=\"katex-eq\" data-katex-display=\"false\">m_2<\/span> and are a distance of <span class=\"katex-eq\" data-katex-display=\"false\">r<\/span> away, then you can calculate the gravitational force between them using the following equation:<\/p>\n\n\n\n<div class=\"wp-block-katex-display-block katex-eq\" data-katex-display=\"true\"><pre>F=G\\frac{m_1m_2}{r^2}<\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The constant <span class=\"katex-eq\" data-katex-display=\"false\">G<\/span> is a gravitational constant. You&#8217;ll see how you&#8217;ll be able to ignore this constant in the version of the simulation you&#8217;ll write in this article in which you&#8217;ll use arbitrary units for mass and distance rather than kg and m.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once you know the gravitational force between two objects, you can work out the acceleration <span class=\"katex-eq\" data-katex-display=\"false\">a<\/span> each object undergoes due to this gravitational force using the following formula:<\/p>\n\n\n\n<div class=\"wp-block-katex-display-block katex-eq\" data-katex-display=\"true\"><pre>F=ma<\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Using this acceleration, you can adjust the velocity of the moving object. When the velocity changes, both the speed and the direction of travel will change.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"representing-points-and-vectors-in-3d\">Representing Points and Vectors in 3D<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">When simulating a 3D solar system in Python, you&#8217;ll need to represent the solar system as a region of space using three dimensions. Therefore, each point in this 3D space can be represented using three numbers, the <em>x<\/em>-, <em>y<\/em>-, and <em>z<\/em>-coordinates. For example, if you wish to place a sun in the centre of the solar system, you can represent the sun&#8217;s position as <em>(0, 0, 0)<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll also need to represent vectors in 3D space. A vector has both magnitude and direction. You&#8217;ll need vectors for quantities such as velocity, acceleration, and force since these quantities all have a direction as well as a magnitude.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I won&#8217;t be discussing vector algebra in detail in this article. Instead, I&#8217;ll state any results that you&#8217;ll need as and when you need them. You can read more about <a href=\"https:\/\/en.wikipedia.org\/wiki\/Vector_(mathematics_and_physics)\">vectors and vector algebra<\/a> if you wish.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To make working with vectors easier in the code, you can create a class to deal with them. Writing this class will serve as a quick refresher on classes and object-oriented programming. You can read about <a href=\"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/\">object-oriented programming in Python<\/a> if you feel you need a more thorough explanation. Although you can also create a class to deal with points in 3D space, this isn&#8217;t necessary, and I won&#8217;t be creating one in this article.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"creating-the-vector-class-aka-reviewing-classes\">Creating The <code>Vector<\/code> Class (aka Reviewing Classes)<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><em>If you&#8217;re familiar with vectors and object-oriented programming, you can skip this section and just review the code at the end defining the <code>Vector<\/code> class.<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Create a new file called <code>vectors.py<\/code> in which you&#8217;ll define the <code>Vector<\/code> class. You&#8217;ll use this script to define the class and test it out. You can then delete the testing code at the end and leave just the class definition in this script:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># vectors.py\n\nclass Vector:\n    def __init__(self, x=0, y=0, z=0):\n        self.x = x\n        self.y = y\n        self.z = z\n\n    def __repr__(self):\n        return f\"Vector({self.x}, {self.y}, {self.z})\"\n\n    def __str__(self):\n        return f\"{self.x}i + {self.y}j + {self.z}k\"\n\n\n# Testing Vector Class - TO BE DELETED\ntest = Vector(3, 5, 9)\nprint(test)\nprint(repr(test))\n\ntest = Vector(2, 2)\nprint(test)\nprint(repr(test))\n\ntest = Vector(y=5, z=3)\nprint(test)\nprint(repr(test))<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>__init__()<\/code> method for the <code>Vector<\/code> class has three parameters representing the value along each axis. Each parameter has a default value of <code>0<\/code> representing the origin for that axis. Although we prefer not to use single letter names in Python, <code>x<\/code>, <code>y<\/code>, and <code>z<\/code> are appropriate as they represent the terms commonly used in mathematics for the Cartesian coordinate system.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ve also defined the two dunder methods to represent the object as a string:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>__repr__()<\/code> returns an output intended for a programmer showing the class name. The output from <code>__repr__()<\/code> can be used to recreate the object.<\/li>\n\n\n\n<li><code>__str__()<\/code> returns a non-programmer&#8217;s version of the string representation of the object. In this case, it returns a representation that&#8217;s commonly used in maths to represent vectors, using the unit vectors <strong>i<\/strong>, <strong>j<\/strong>, and <strong>k<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You can read more about the differences between the two types of string representations in the Snippets section at the end of <a href=\"https:\/\/thepythoncodingbook.com\/dates-and-times-in-python\/\">Chapter 9 in The Python Coding Book<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The output from the testing code block is the following:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">3i + 5j + 9k\nVector(3, 5, 9)\n2i + 2j + 0k\nVector(2, 2, 0)\n0i + 5j + 3k\nVector(0, 5, 3)<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"making-the-vector-class-indexable\">Making the <code>Vector<\/code> class indexable<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In this 3D solar system in Python project, it would be convenient if the <code>Vector<\/code> class was indexable so that you can use the <code>[]<\/code> notation with an index to extract one of the values. With the class in its current form, if you add <code>print(test[0])<\/code> in your script, you&#8217;ll get a <code>TypeError<\/code> saying that the <code>Vector<\/code> object is not subscriptable. You can fix this by adding another dunder method to the class definition:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"15-23,27-29\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># vectors.py\n\nclass Vector:\n    def __init__(self, x=0, y=0, z=0):\n        self.x = x\n        self.y = y\n        self.z = z\n\n    def __repr__(self):\n        return f\"Vector({self.x}, {self.y}, {self.z})\"\n\n    def __str__(self):\n        return f\"{self.x}i + {self.y}j + {self.z}k\"\n\n    def __getitem__(self, item):\n        if item == 0:\n            return self.x\n        elif item == 1:\n            return self.y\n        elif item == 2:\n            return self.z\n        else:\n            raise IndexError(\"There are only three elements in the vector\")\n\n\n# Testing Vector Class - TO BE DELETED\ntest = Vector(3, 5, 9)\n\nprint(test[0])<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">By defining <code>__getitem__()<\/code>, you&#8217;ve made the <code>Vector<\/code> class indexable. The first item in a vector is the value of <em>x<\/em>, the second is the value of <em>y<\/em>, and the third is the value of <em>z<\/em>. Any other index will raise an error. The output from the testing code block is the following:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">3<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>test[0]<\/code> returns the first item in the vector, the value for <em>x<\/em>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"defining-addition-and-subtraction-in-the-vector-class\">Defining addition and subtraction in the <code>Vector<\/code> class<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You can define addition and subtraction for objects of a class by defining the <code>__add__()<\/code> and <code>__sub__()<\/code> dunder methods. These methods will enable you to use the <code>+<\/code> and <code>-<\/code> symbols to perform these operations. Without these dunder methods, using <code>+<\/code> and <code>-<\/code> raises a <code>TypeError<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To add or subtract two vectors, you can add or subtract each element of the vectors separately:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"25-37,40-45\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># vectors.py\n\nclass Vector:\n    def __init__(self, x=0, y=0, z=0):\n        self.x = x\n        self.y = y\n        self.z = z\n\n    def __repr__(self):\n        return f\"Vector({self.x}, {self.y}, {self.z})\"\n\n    def __str__(self):\n        return f\"{self.x}i + {self.y}j + {self.z}k\"\n\n    def __getitem__(self, item):\n        if item == 0:\n            return self.x\n        elif item == 1:\n            return self.y\n        elif item == 2:\n            return self.z\n        else:\n            raise IndexError(\"There are only three elements in the vector\")\n\n    def __add__(self, other):\n        return Vector(\n            self.x + other.x,\n            self.y + other.y,\n            self.z + other.z,\n        )\n\n    def __sub__(self, other):\n        return Vector(\n            self.x - other.x,\n            self.y - other.y,\n            self.z - other.z,\n        )\n\n# Testing Vector Class - TO BE DELETED\ntest = Vector(3, 5, 9) + Vector(1, -3, 2)\nprint(test)\n\n\ntest = Vector(3, 5, 9) - Vector(1, -3, 2)\nprint(test)<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Both <code>__add__()<\/code> and <code>__sub__()<\/code> return another <code>Vector<\/code> object with each element equal to the addition or subtraction of the respective elements in the two original vectors. The output is the following:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">4i + 2j + 11k\n2i + 8j + 7k<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can do the same for multiplication and division, although these operations need more care when dealing with vectors.<\/p>\n\n\n\n<div class=\"wp-block-group\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-group alignfull\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-group alignfull\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-coblocks-hero alignfull coblocks-hero-230194844519\"><div class=\"wp-block-coblocks-hero__inner has-background hero-center-left-align has-padding has-huge-padding\" style=\"background-color:#1a6b72;min-height:500px\"><div class=\"wp-block-coblocks-hero__content-wrapper\"><div class=\"wp-block-coblocks-hero__content\" style=\"max-width:560px\">\n<h2 class=\"wp-block-heading has-text-color has-link-color wp-elements-806dd89de56256fb948e5020de497de4\" style=\"color:#fff3e6\">Become a Member of<\/h2>\n\n\n\n<h2 class=\"wp-block-heading has-text-color has-link-color wp-elements-7d78fcf199c064aa3173690e46837383\" style=\"color:#fff3e6\">The Python Coding Place<\/h2>\n\n\n\n<p class=\"has-text-color has-link-color wp-elements-57091ca0dd26b2b579f184ab1723dc89 wp-block-paragraph\" style=\"color:#fff3e6\">Video courses, live cohort-based courses, workshops, weekly videos, members&#8217; forum, and more\u2026<\/p>\n\n\n\n<div style=\"height:66px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-50\"><a class=\"wp-block-button__link has-black-color has-text-color has-background wp-element-button\" href=\"https:\/\/thepythoncodingplace.com\" style=\"background-color:#fdb33b\">Become a Member<\/a><\/div>\n<\/div>\n<\/div><\/div><\/div><\/div>\n<\/div><\/div>\n<\/div><\/div>\n<\/div><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"defining-scalar-multiplication-dot-product-and-scalar-division-in-the-vector-class\">Defining scalar multiplication, dot product and scalar division in the <code>Vector<\/code> class<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You cannot just refer to &#8216;multiplication&#8217; when dealing with vectors as there are different types of &#8216;multiplication&#8217;. In this project, you&#8217;ll only need <a href=\"https:\/\/en.wikipedia.org\/wiki\/Scalar_multiplication\">scalar multiplication<\/a>. Scalar multiplication is when a vector is multiplied by a scalar (which has a magnitude but no direction). However, in this subsection, you&#8217;ll also define the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Dot_product\">dot product<\/a> of two vectors. You&#8217;d like to use the <code>*<\/code> operator for both scalar multiplication and the dot product. Therefore, you can define the <code>__mul__()<\/code> dunder method:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"39-53,56-57\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># vectors.py\n\nclass Vector:\n    def __init__(self, x=0, y=0, z=0):\n        self.x = x\n        self.y = y\n        self.z = z\n\n    def __repr__(self):\n        return f\"Vector({self.x}, {self.y}, {self.z})\"\n\n    def __str__(self):\n        return f\"{self.x}i + {self.y}j + {self.z}k\"\n\n    def __getitem__(self, item):\n        if item == 0:\n            return self.x\n        elif item == 1:\n            return self.y\n        elif item == 2:\n            return self.z\n        else:\n            raise IndexError(\"There are only three elements in the vector\")\n\n    def __add__(self, other):\n        return Vector(\n            self.x + other.x,\n            self.y + other.y,\n            self.z + other.z,\n        )\n\n    def __sub__(self, other):\n        return Vector(\n            self.x - other.x,\n            self.y - other.y,\n            self.z - other.z,\n        )\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):  # Vector dot product\n            return (\n                self.x * other.x\n                + self.y * other.y\n                + self.z * other.z\n            )\n        elif isinstance(other, (int, float)):  # Scalar multiplication\n            return Vector(\n                self.x * other,\n                self.y * other,\n                self.z * other,\n            )\n        else:\n            raise TypeError(\"operand must be Vector, int, or float\")\n\n# Testing Vector Class - TO BE DELETED\ntest = Vector(3, 5, 9) * Vector(1, -3, 2)\nprint(test)\n\n\ntest = Vector(3, 5, 9) * 3\nprint(test)<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The result of using the <code>*<\/code> operator will depend on whether the second operand, the one following the <code>*<\/code> symbol, is a scalar or a vector. If the second operand, represented by the parameter <code>other<\/code>, is of type <code>Vector<\/code>, the dot product is calculated. However, if <code>other<\/code> is of type <code>int<\/code> or <code>float<\/code>, the returned result is a new <code>Vector<\/code>, scaled accordingly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The output from the code above is the following:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">6\n9i + 15j + 27k<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If you want scalar multiplication, the scalar needs to come <em>after<\/em> the <code>*<\/code> symbol. If you attempt to run the statement <code>3*Vector(3, 5, 9)<\/code> instead, a <code>TypeError<\/code> will be raised since the <code>Vector<\/code> class is not a valid operand for using <code>*<\/code> with objects of type <code>int<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Two vectors cannot be divided. However, you can divide a vector by a scalar. You can use the <code>\/<\/code> operator with the <code>Vector<\/code> class if you define the <code>__truediv__()<\/code> dunder method:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"55-63,66-67\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># vectors.py\n\nclass Vector:\n    def __init__(self, x=0, y=0, z=0):\n        self.x = x\n        self.y = y\n        self.z = z\n\n    def __repr__(self):\n        return f\"Vector({self.x}, {self.y}, {self.z})\"\n\n    def __str__(self):\n        return f\"{self.x}i + {self.y}j + {self.z}k\"\n\n    def __getitem__(self, item):\n        if item == 0:\n            return self.x\n        elif item == 1:\n            return self.y\n        elif item == 2:\n            return self.z\n        else:\n            raise IndexError(\"There are only three elements in the vector\")\n\n    def __add__(self, other):\n        return Vector(\n            self.x + other.x,\n            self.y + other.y,\n            self.z + other.z,\n        )\n\n    def __sub__(self, other):\n        return Vector(\n            self.x - other.x,\n            self.y - other.y,\n            self.z - other.z,\n        )\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):  # Vector dot product\n            return (\n                self.x * other.x\n                + self.y * other.y\n                + self.z * other.z\n            )\n        elif isinstance(other, (int, float)):  # Scalar multiplication\n            return Vector(\n                self.x * other,\n                self.y * other,\n                self.z * other,\n            )\n        else:\n            raise TypeError(\"operand must be Vector, int, or float\")\n\n    def __truediv__(self, other):\n        if isinstance(other, (int, float)):\n            return Vector(\n                self.x \/ other,\n                self.y \/ other,\n                self.z \/ other,\n            )\n        else:\n            raise TypeError(\"operand must be int or float\")\n\n# Testing Vector Class - TO BE DELETED\ntest = Vector(3, 6, 9) \/ 3\nprint(test)<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">And the output is:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">1.0i + 2.0j + 3.0k<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"finding-the-magnitude-of-a-vector-and-normalizing-a-vector\">Finding the magnitude of a vector and normalizing a vector<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If you have a vector <span class=\"katex-eq\" data-katex-display=\"false\"> (x, y, z)<\/span>, you can find its <a href=\"https:\/\/en.wikipedia.org\/wiki\/Magnitude_(mathematics)#Vector_spaces\">magnitude<\/a> using the expression <span class=\"katex-eq\" data-katex-display=\"false\">\\sqrt(x^2 +y^2 + z^2)<\/span>. You can also <a href=\"https:\/\/en.wikipedia.org\/wiki\/Unit_vector\">normalize a vector<\/a>. Normalization gives a vector with the same direction but with a magnitude of <code>1<\/code>. You can calculate the normalized vector by dividing each element of the vector by the vector&#8217;s magnitude.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can define two new methods to complete the <code>Vector<\/code> class:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"3,67-76,79-82\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># vectors.py\n\nimport math\n\nclass Vector:\n    def __init__(self, x=0, y=0, z=0):\n        self.x = x\n        self.y = y\n        self.z = z\n\n    def __repr__(self):\n        return f\"Vector({self.x}, {self.y}, {self.z})\"\n\n    def __str__(self):\n        return f\"{self.x}i + {self.y}j + {self.z}k\"\n\n    def __getitem__(self, item):\n        if item == 0:\n            return self.x\n        elif item == 1:\n            return self.y\n        elif item == 2:\n            return self.z\n        else:\n            raise IndexError(\"There are only three elements in the vector\")\n\n    def __add__(self, other):\n        return Vector(\n            self.x + other.x,\n            self.y + other.y,\n            self.z + other.z,\n        )\n\n    def __sub__(self, other):\n        return Vector(\n            self.x - other.x,\n            self.y - other.y,\n            self.z - other.z,\n        )\n\n    def __mul__(self, other):\n        if isinstance(other, Vector):  # Vector dot product\n            return (\n                self.x * other.x\n                + self.y * other.y\n                + self.z * other.z\n            )\n        elif isinstance(other, (int, float)):  # Scalar multiplication\n            return Vector(\n                self.x * other,\n                self.y * other,\n                self.z * other,\n            )\n        else:\n            raise TypeError(\"operand must be Vector, int, or float\")\n\n    def __truediv__(self, other):\n        if isinstance(other, (int, float)):\n            return Vector(\n                self.x \/ other,\n                self.y \/ other,\n                self.z \/ other,\n            )\n        else:\n            raise TypeError(\"operand must be int or float\")\n\n    def get_magnitude(self):\n        return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)\n\n    def normalize(self):\n        magnitude = self.get_magnitude()\n        return Vector(\n            self.x \/ magnitude,\n            self.y \/ magnitude,\n            self.z \/ magnitude,\n        )\n\n# Testing Vector Class - TO BE DELETED\ntest = Vector(3, 6, 9)\nprint(test.get_magnitude())\nprint(test.normalize())\nprint(test.normalize().get_magnitude())<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The testing code gives the following output:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">11.224972160321824\n0.2672612419124244i + 0.5345224838248488j + 0.8017837257372732k\n1.0<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The third output gives the magnitude of the normalized vector, showing that its magnitude is <code>1<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Depending on what IDE or other tools you&#8217;re using, you may get a warning when dividing <code>self.x<\/code>, <code>self.y<\/code>, and <code>self.z<\/code>, such as in <code>__truediv__()<\/code> and <code>normalize()<\/code>. You don&#8217;t need to worry about this, but if you&#8217;d like to fix it, you can do so by changing the <code>__init__()<\/code> signature to either of the following:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def __init__(self, x=0.0, y=0.0, z=0.0):<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">or<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def __init__(self, x:float=0, y:float=0, z:float=0):<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Both options let your IDE know that the arguments should be floats. In the second option, you&#8217;re using type-hinting to do so.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can now delete the testing code at the end of this script so that all you have in <code>vectors.py<\/code> is the class definition.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"simulating-a-3d-solar-system-in-python\">Simulating a 3D Solar System in Python<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now, you can start working on the 3D solar system in Python. You&#8217;ll create two main classes:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>SolarSystem<\/code>: this class takes care of the solar system, keeps track of how many bodies there are within it and the interactions between them.<\/li>\n\n\n\n<li><code>SolarSystemBody<\/code>: this class deals with each individual body in the solar system and the body&#8217;s movement.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll use Matplotlib to create and visualise the solar system. You can install Matplotlib by using the following in the Terminal:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$ pip install matplotlib<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">or<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$ python -m pip install matplotlib<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>Axes3D<\/code> object in Matplotlib will &#8216;host&#8217; the solar system. If you&#8217;ve used Matplotlib and mostly used 2D plots, you would have used (knowingly or unknowingly) the <code>Axes<\/code> object. <code>Axes3D<\/code> is the 3D equivalent of <code>Axes<\/code>, as the name implies!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It&#8217;s time to get started writing and testing these classes. You can create two new files:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>solar_system_3d.py<\/code> will contain the class definitions.<\/li>\n\n\n\n<li><code>simple_solar_system.py<\/code> will contain the code to create a solar system. You&#8217;ll use this file to test the classes as you write them, leading towards creating a simple solar system with one sun and two orbiting planets.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Next, you&#8217;ll start working on the <code>SolarSystem<\/code> class.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"setting-up-the-solarsystem-class\">Setting up the <code>SolarSystem<\/code> class<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll use arbitrary units throughout this project. This means that rather than using meters for distances and kilograms for masses, you&#8217;ll use quantities with no units. The parameter <code>size<\/code> is used to define the size of the cube that will contain the solar system:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nclass SolarSystem:\n    def __init__(self, size):\n        self.size = size\n        self.bodies = []\n\n    def add_body(self, body):\n        self.bodies.append(body)<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You define the <code>SolarSystem<\/code> class with an <code>__init__()<\/code> method which includes the parameter <code>size<\/code>. You also define the <code>bodies<\/code> attribute. This attribute is an empty list that will contain all the bodies within the solar system when you create them later on. The <code>add_body()<\/code> method can be used to add orbiting bodies to the solar system.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The next step is to introduce Matplotlib. You can create a figure and a set of axes using the <code>subplots()<\/code> function in <code>matplotlib.pyplot<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"3,10-16\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport matplotlib.pyplot as plt\n\nclass SolarSystem:\n    def __init__(self, size):\n        self.size = size\n        self.bodies = []\n\n        self.fig, self.ax = plt.subplots(\n            1,\n            1,\n            subplot_kw={\"projection\": \"3d\"},\n            figsize=(self.size \/ 50, self.size \/ 50),\n        )\n        self.fig.tight_layout()\n\n    def add_body(self, body):\n        self.bodies.append(body)<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You call <code>plt.subplots()<\/code>, which returns a figure and a set of axes. The values returned are assigned to the attributes <code>fig<\/code> and <code>ax<\/code>. You call <code>plt.subplots()<\/code> with the following arguments:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The first two arguments are <code>1<\/code> and <code>1<\/code> to create a single set of axes in the figure.<\/li>\n\n\n\n<li>The <code>subplot_kw<\/code> parameter has a dictionary as its argument, which sets the projection to 3D. This means the axes created are an <code>Axes3D<\/code> object.<\/li>\n\n\n\n<li><code>figsize<\/code> sets the overall size of the figure containing the <code>Axes3D<\/code> object.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You also call the method <code>tight_layout()<\/code>. This is a method of the <code>Figure<\/code> class in Matplotlib. This method reduces the margins at the edge of the figure.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can try the code so far in the Console\/REPL:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> import matplotlib.pyplot as plt\n>>> from solar_system_3d import SolarSystem\n\n>>> solar_system = SolarSystem(400)\n>>> plt.show()  # if not using interactive mode<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This gives a figure with an empty set of 3D axes:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"739\" height=\"739\" data-attachment-id=\"1813\" data-permalink=\"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/empty_axes\/\" data-orig-file=\"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?fit=1600%2C1600&amp;ssl=1\" data-orig-size=\"1600,1600\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"empty_axes\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?fit=739%2C739&amp;ssl=1\" src=\"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?resize=739%2C739&#038;ssl=1\" alt=\"\" class=\"wp-image-1813\" style=\"width:512px;height:512px\" srcset=\"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?resize=1024%2C1024&amp;ssl=1 1024w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?resize=300%2C300&amp;ssl=1 300w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?resize=150%2C150&amp;ssl=1 150w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?resize=768%2C768&amp;ssl=1 768w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?resize=1536%2C1536&amp;ssl=1 1536w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?resize=1200%2C1200&amp;ssl=1 1200w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?resize=800%2C800&amp;ssl=1 800w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?resize=400%2C400&amp;ssl=1 400w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?resize=200%2C200&amp;ssl=1 200w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?resize=1088%2C1088&amp;ssl=1 1088w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?w=1600&amp;ssl=1 1600w, https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/empty_axes.png?w=1478&amp;ssl=1 1478w\" sizes=\"auto, (max-width: 739px) 100vw, 739px\" \/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll use the <code>size<\/code> parameter later to set the size of this cube. You&#8217;ll return to the <code>SolarSystem<\/code> class later. For the time being, you can turn your attention to defining the <code>SolarSystemBody<\/code> class.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"setting-up-the-solarsystembody-class\">Setting up the <code>SolarSystemBody<\/code> class<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You can start creating the <code>SolarSystemBody<\/code> class and its <code>__init__()<\/code> method. I&#8217;m truncating the code in the <code>SolarSystem<\/code> class definition in the code below for display purposes. In this and later code blocks, the lines containing <code># ...<\/code> indicate code you&#8217;ve already written earlier that&#8217;s not being displayed:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"5,10-23\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport matplotlib.pyplot as plt\n\nfrom vectors import Vector\n\n# class SolarSystem:\n# ...  \n\nclass SolarSystemBody:\n    def __init__(\n        self,\n        solar_system,\n        mass,\n        position=(0, 0, 0),\n        velocity=(0, 0, 0),\n    ):\n        self.solar_system = solar_system\n        self.mass = mass\n        self.position = position\n        self.velocity = Vector(*velocity)\n\n        self.solar_system.add_body(self)<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The parameters in the <code>__init__()<\/code> method are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>solar_system<\/code> enables you to link the body to a solar system. The argument should be of type <code>SolarSystem<\/code>.<\/li>\n\n\n\n<li><code>mass<\/code> is an integer or float that defines the body&#8217;s mass. In this project, you&#8217;ll use arbitrary units, so you don&#8217;t need to use &#8216;real&#8217; masses for stars and planets.<\/li>\n\n\n\n<li><code>position<\/code> is a point in 3D space defining the body&#8217;s position. It&#8217;s a tuple containing the <em>x<\/em>-, <em>y<\/em>-, and <em>z<\/em>-coordinates of the point. The default is the origin.<\/li>\n\n\n\n<li><code>velocity<\/code> defines the velocity of the body. Since the velocity of a moving body has magnitude and direction, it must be a vector. Although the argument needed when instantiating a <code>SolarSystemBody<\/code> is a tuple, you can convert the tuple into a <code>Vector<\/code> object when assigning it to the attribute <code>self.velocity<\/code>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You also call the <code>add_body()<\/code> method you defined earlier in the <code>SolarSystem<\/code> class to add this body to the solar system. Later on, you&#8217;ll add a bit more to the <code>__init__()<\/code> method.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can define another method in <code>SolarSystemBody<\/code> to move the body using its current position and velocity:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"25-30\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport matplotlib.pyplot as plt\n\nfrom vectors import Vector\n\n# class SolarSystem:\n# ... \n\nclass SolarSystemBody:\n    def __init__(\n        self,\n        solar_system,\n        mass,\n        position=(0, 0, 0),\n        velocity=(0, 0, 0),\n    ):\n        self.solar_system = solar_system\n        self.mass = mass\n        self.position = position\n        self.velocity = Vector(*velocity)\n\n        self.solar_system.add_body(self)\n\n    def move(self):\n        self.position = (\n            self.position[0] + self.velocity[0],\n            self.position[1] + self.velocity[1],\n            self.position[2] + self.velocity[2],\n        )<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>move()<\/code> method redefines the <code>position<\/code> attribute based on the <code>velocity<\/code> attribute. We&#8217;ve already discussed how you&#8217;re using arbitrary units for distance and mass. You&#8217;re also using arbitrary units for time. Each &#8216;time unit&#8217; will be one iteration of the loop you&#8217;ll use to run the simulation. Therefore, <code>move()<\/code> will shift the body by the amount required for one iteration, which is one time unit.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"drawing-the-solar-system-bodies\">Drawing the solar system bodies<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ve already created the Matplotlib structures that will hold the solar system and all its bodies. Now, you can add a <code>draw()<\/code> method to <code>SolarSystemBody<\/code> to display the body on the Matplotlib plot. You can do this by drawing a marker.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Before you do so, you&#8217;ll need to define a few more attributes in <code>SolarSystemBody<\/code> to control the colour and size of the markers that you&#8217;ll draw to represent the bodies:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"3,12-13,26-30,41-47\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport math\nimport matplotlib.pyplot as plt\n\nfrom vectors import Vector\n\n# class SolarSystem:\n# ... \n\nclass SolarSystemBody:\n    min_display_size = 10\n    display_log_base = 1.3\n\n    def __init__(\n        self,\n        solar_system,\n        mass,\n        position=(0, 0, 0),\n        velocity=(0, 0, 0),\n    ):\n        self.solar_system = solar_system\n        self.mass = mass\n        self.position = position\n        self.velocity = Vector(*velocity)\n        self.display_size = max(\n            math.log(self.mass, self.display_log_base),\n            self.min_display_size,\n        )\n        self.colour = \"black\"\n\n        self.solar_system.add_body(self)\n\n    def move(self):\n        self.position = (\n            self.position[0] + self.velocity[0],\n            self.position[1] + self.velocity[1],\n            self.position[2] + self.velocity[2],\n        )\n\n    def draw(self):\n        self.solar_system.ax.plot(\n            *self.position,\n            marker=\"o\",\n            markersize=self.display_size,\n            color=self.colour\n        )<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The class attributes <code>min_display_size<\/code> and <code>display_log_base<\/code> set up the parameters for determining the size of the markers you&#8217;ll display on the 3D plot. You set a minimum size so that the marker you display is not too small, even for small bodies. You&#8217;ll use a logarithmic scale to convert from mass to marker size, and you set the base for this logarithm as another class attribute.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>display_size<\/code> instance attribute in the <code>__init__()<\/code> method chooses between the calculated marker size and the minimum marker size you set. To determine the body&#8217;s display size in this project, you&#8217;re using its mass.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You also add the <code>colour<\/code> attribute in <code>__init__()<\/code>, which, for the time being, defaults to black.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To test these new additions, you can try the following in the Console\/REPL:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> import matplotlib.pyplot as plt\n>>> from solar_system_3d import SolarSystem, SolarSystemBody\n\n>>> solar_system = SolarSystem(400)\n>>> plt.show()  # if not using interactive mode\n\n>>> body = SolarSystemBody(solar_system, 100, velocity=(1, 1, 1))\n\n>>> body.draw()\n>>> body.move()\n>>> body.draw()<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The first call to <code>body.draw()<\/code> draws the body at the origin since you&#8217;re using the default position for a solar system body. The call to <code>body.move()<\/code> moves the body by the amount required for one &#8216;time unit&#8217;. Since the body&#8217;s velocity is <code>(1, 1, 1)<\/code>, the body will move by one unit along each of the three axes. The second call to <code>body.draw()<\/code> draws the solar system body in the second position. Note that the axes will automatically rescale when you do this. You&#8217;ll take care of this in the main code shortly.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"moving-stars-and-planets\">Moving Stars and Planets<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You can return to the <code>SolarSystem<\/code> class and link the solar system and its bodies further by adding two new methods to the class: <code>update_all()<\/code> and <code>draw_all()<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"24-34\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport math\nimport matplotlib.pyplot as plt\n\nfrom vectors import Vector\n\nclass SolarSystem:\n    def __init__(self, size):\n        self.size = size\n        self.bodies = []\n\n        self.fig, self.ax = plt.subplots(\n            1,\n            1,\n            subplot_kw={\"projection\": \"3d\"},\n            figsize=(self.size \/ 50, self.size \/ 50),\n        )\n        self.fig.tight_layout()\n\n    def add_body(self, body):\n        self.bodies.append(body)\n\n    def update_all(self):\n        for body in self.bodies:\n            body.move()\n            body.draw()\n\n    def draw_all(self):\n        self.ax.set_xlim((-self.size \/ 2, self.size \/ 2))\n        self.ax.set_ylim((-self.size \/ 2, self.size \/ 2))\n        self.ax.set_zlim((-self.size \/ 2, self.size \/ 2))\n        plt.pause(0.001)\n        self.ax.clear()\n\n# class SolarSystemBody:\n# ...<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>update_all()<\/code> method goes through each body in the solar system and moves and draws each body. The <code>draw_all()<\/code> method sets the limits for the three axes using the solar system&#8217;s size and updates the plot through the <code>pause()<\/code> function. This method also clears the axes, ready for the next plot.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can start building a simple solar system and test the code you&#8217;ve written so far by creating a new script called <code>simple_solar_system.py<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># simple_solar_system.py\n\nfrom solar_system_3d import SolarSystem, SolarSystemBody\n\nsolar_system = SolarSystem(400)\n\nbody = SolarSystemBody(solar_system, 100, velocity=(1, 1, 1))\n\nfor _ in range(100):\n    solar_system.update_all()\n    solar_system.draw_all()<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When you run this script, you&#8217;ll see a black body moving away from the centre of the plot:<\/p>\n\n\n\n<figure class=\"wp-block-video wp-block-embed is-type-video is-provider-videopress\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"VideoPress Video Player\" aria-label='VideoPress Video Player' width='739' height='416' src='https:\/\/videopress.com\/embed\/DpkGSRqX?cover=1&amp;preloadContent=metadata&amp;hd=0' frameborder='0' allowfullscreen data-resize-to-parent=\"true\" allow='clipboard-write'><\/iframe><script src='https:\/\/v0.wordpress.com\/js\/next\/videopress-iframe.js?m=1725245713'><\/script>\n<\/div><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">You can change the perspective of the 3D plot so that you&#8217;re viewing the 3D axes directly along one of the axes. You can do so by setting both the azimuth and the elevation of the view to <code>0<\/code> in <code>SolarSystem.__init__()<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"20\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport math\nimport matplotlib.pyplot as plt\n\nfrom vectors import Vector\n\nclass SolarSystem:\n    def __init__(self, size):\n        self.size = size\n        self.bodies = []\n\n        self.fig, self.ax = plt.subplots(\n            1,\n            1,\n            subplot_kw={\"projection\": \"3d\"},\n            figsize=(self.size \/ 50, self.size \/ 50),\n        )\n        self.fig.tight_layout()\n        self.ax.view_init(0, 0)\n\n    def add_body(self, body):\n        self.bodies.append(body)\n\n    def update_all(self):\n        for body in self.bodies:\n            body.move()\n            body.draw()\n\n    def draw_all(self):\n        self.ax.set_xlim((-self.size \/ 2, self.size \/ 2))\n        self.ax.set_ylim((-self.size \/ 2, self.size \/ 2))\n        self.ax.set_zlim((-self.size \/ 2, self.size \/ 2))\n        plt.pause(0.001)\n        self.ax.clear()\n\n# class SolarSystemBody:\n# ...<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Running <code>simple_solar_system.py<\/code> now gives the following view:<\/p>\n\n\n\n<figure class=\"wp-block-video wp-block-embed is-type-video is-provider-videopress\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"VideoPress Video Player\" aria-label='VideoPress Video Player' width='739' height='416' src='https:\/\/videopress.com\/embed\/fs4Fbm1b?cover=1&amp;preloadContent=metadata&amp;hd=0' frameborder='0' allowfullscreen data-resize-to-parent=\"true\" allow='clipboard-write'><\/iframe><script src='https:\/\/v0.wordpress.com\/js\/next\/videopress-iframe.js?m=1725245713'><\/script>\n<\/div><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The <em>x<\/em>-axis is now perpendicular to your screen. Since you&#8217;re displaying a 3D view on a 2D display, you&#8217;ll always have one direction which is perpendicular to the 2D plane you&#8217;re using to display the plot. This restriction can make it hard to distinguish when an object is moving along that axis. You can see this by changing the body&#8217;s velocity in <code>simple_solar_system.py<\/code> to <code>(1, 0, 0)<\/code> and running the script again. The body appears stationary since it&#8217;s only moving along the axis coming out of your screen!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"helping-with-the-3d-perspective\">Helping with the 3D perspective<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You can improve the 3D visualisation by changing the size of the marker depending on its <em>x<\/em>-coordinate. Objects closer to you appear larger, and objects further away appear smaller. You can make a change to the <code>draw()<\/code> method in the <code>SolarSystemBody<\/code> class:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"11\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n# ...\n\nclass SolarSystemBody:\n# ...\n\n    def draw(self):\n        self.solar_system.ax.plot(\n            *self.position,\n            marker=\"o\",\n            markersize=self.display_size + self.position[0] \/ 30,\n            color=self.colour\n        )<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>self.position[0]<\/code> represents the body&#8217;s position along the <em>x<\/em>-axis, which is the one perpendicular to the screen. The factor of <code>30<\/code> you divide by is an arbitrary factor you can use to control how strong you want this effect to be.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Later in this tutorial, you&#8217;ll also add another feature that will help visualise the 3D motion of the stars and planets.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"adding-the-effects-of-gravity\">Adding The Effects Of Gravity<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You have a solar system with bodies that can move within it. The code so far works fine if you have a single body. But that&#8217;s not a very interesting solar system! If you have two or more bodies, they will interact through their mutual gravitational attraction.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Toward the beginning of this article, I briefly reviewed the physics you&#8217;ll need to deal with the gravitational force between two objects. Since you&#8217;re using arbitrary units in this project, you can ignore the gravitational constant <em>G<\/em> and simply work out the force due to gravity between two objects as:<\/p>\n\n\n\n<div class=\"wp-block-katex-display-block katex-eq\" data-katex-display=\"true\"><pre>F=\\frac{m_1m_1}{r^2}<\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">Once you know the force between two objects, since <span class=\"katex-eq\" data-katex-display=\"false\">F=ma<\/span>, you can work out the acceleration that each object is subject to using:<\/p>\n\n\n\n<div class=\"wp-block-katex-display-block katex-eq\" data-katex-display=\"true\"><pre>a=\\frac{F}{m}<\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">And once you know the acceleration, you can change the object&#8217;s velocity.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can add two new methods, one in <code>SolarSystemBody<\/code> and another in <code>SolarSystem<\/code>, to work out the force and acceleration between any two bodies and to go through all the bodies in the solar system and work out the interactions between them.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"working-out-the-acceleration-due-to-gravity\">Working out the acceleration due to gravity<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The first of these methods works out the gravitational force between two bodies, calculates the acceleration of each of the bodies and changes the velocities of the two bodies. You can split these tasks into three methods if you prefer, but in this example, I&#8217;ll put these tasks into a single method in <code>SolarSystemBody<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"14-25\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport math\nimport matplotlib.pyplot as plt\n\nfrom vectors import Vector\n\n# class SolarSystem:\n# ...\n\nclass SolarSystemBody:\n# ...\n\n    def accelerate_due_to_gravity(self, other):\n        distance = Vector(*other.position) - Vector(*self.position)\n        distance_mag = distance.get_magnitude()\n\n        force_mag = self.mass * other.mass \/ (distance_mag ** 2)\n        force = distance.normalize() * force_mag\n\n        reverse = 1\n        for body in self, other:\n            acceleration = force \/ body.mass\n            body.velocity += acceleration * reverse\n            reverse = -1<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>accelerate_due_to_gravity()<\/code> is called on an object of type <code>SolarSystemBody<\/code> and needs another <code>SolarSystemBody<\/code> body as an argument. The parameters <code>self<\/code> and <code>other<\/code> represent the two bodies interacting with each other. The steps in this method are the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The positions of the two bodies are used to find the distance between the two bodies. You represent this as a vector since both its magnitude and direction are important. You extract the <em>x<\/em>-, <em>y<\/em>-, and <em>z<\/em>&#8211; values from the <code>position<\/code> attribute using the unpacking operator <code>*<\/code> and convert these into objects of type <code>Vector<\/code>, which you defined earlier. Since you defined the <code>__sub__()<\/code> dunder method for the <code>Vector<\/code> class, you can subtract one vector from the other to get the distance between them as another vector.<\/li>\n\n\n\n<li>You also calculate the magnitude of the distance vector using the <code>get_magnitude()<\/code> method of the <code>Vector<\/code> class.<\/li>\n\n\n\n<li>Next, you work out the magnitude of the force between the two bodies using the equation summarised above.<\/li>\n\n\n\n<li>However, the force has a direction as well as a magnitude. Therefore, you need to represent it as a vector. The direction of the force is the same as the direction of the vector connecting the two objects. You obtain the force vector by first normalizing the distance vector. This normalization gives a unit vector with the same direction as the vector connecting the two bodies but with a magnitude of <code>1<\/code>. Then, you multiply the unit vector by the magnitude of the force. You&#8217;re using scalar multiplication of a vector in this case which you defined when you included <code>__mul__()<\/code> in the <code>Vector<\/code> class.<\/li>\n\n\n\n<li>For each of the two bodies, you work out the acceleration using the equation shown above. <code>force<\/code> is a vector. Therefore, when you divide by <code>body.mass<\/code>, you&#8217;re using the scalar division you defined when you included <code>__truediv__()<\/code> in the <code>Vector<\/code> class. <code>acceleration<\/code> is the object returned by <code>Vector.__truediv__()<\/code>, which is also a <code>Vector<\/code> object.<\/li>\n\n\n\n<li>Finally, you increment the velocity using the acceleration. This method works out the values relevant for one time unit, which in this simulation is the time it takes for one iteration of the loop that will control the simulation. The <code>reverse<\/code> parameter ensures the opposite acceleration is applied to the second body since the two bodies are being pulled towards each other. The <code>*<\/code> operator again calls <code>Vector.__mul__()<\/code> and results in scalar multiplication.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"calculating-the-interactions-between-all-bodies-in-the-solar-system\">Calculating the interactions between all bodies in the solar system<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Now that you&#8217;re able to work out the interaction between any two bodies, you can work out the interaction between all the bodies present in the solar system. You can shift your attention back to the <code>SolarSystem<\/code> class for this:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"11-15\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport math\nimport matplotlib.pyplot as plt\n\nfrom vectors import Vector\n\nclass SolarSystem:\n# ...\n\n    def calculate_all_body_interactions(self):\n        bodies_copy = self.bodies.copy()\n        for idx, first in enumerate(bodies_copy):\n            for second in bodies_copy[idx + 1:]:\n                first.accelerate_due_to_gravity(second)\n\nclass SolarSystemBody:\n# ...\n\n    def accelerate_due_to_gravity(self, other):\n        distance = Vector(*other.position) - Vector(*self.position)\n        distance_mag = distance.get_magnitude()\n\n        force_mag = self.mass * other.mass \/ (distance_mag ** 2)\n        force = distance.normalize() * force_mag\n\n        reverse = 1\n        for body in self, other:\n            acceleration = force \/ body.mass\n            body.velocity += acceleration * reverse\n            reverse = -1<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>calculate_all_body_interactions()<\/code> method goes through all the bodies in the solar system. Each body interacts with every other body in the solar system:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>You&#8217;re using a copy of <code>self.bodies<\/code> to cater for the possibility that bodies will be removed from the solar system during the loop. <em>In the version you&#8217;re writing in this article, you won&#8217;t remove any bodies from the solar system. However, you may need to do so in the future if you expand this project further.<\/em><\/li>\n\n\n\n<li>To ensure your code doesn&#8217;t calculate the interactions between the same two bodies twice, you only work out the interactions between a body and those bodies that follow it in the list. This is why you&#8217;re using the slice <code>idx + 1:<\/code> in the second <code>for<\/code> loop.<\/li>\n\n\n\n<li>The final line calls <code>accelerate_due_to_gravity()<\/code> for the first body and includes the second body as the method&#8217;s argument.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Now, you&#8217;re ready to create a simple solar system and test the code you&#8217;ve written so far.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"creating-a-simple-solar-system\">Creating A Simple Solar System<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this project, you&#8217;ll focus on creating one of two types of bodies: suns and planets. You can create two classes for these bodies. The new classes inherit from <code>SolarSystemBody<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"3,15-37\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport itertools\nimport math\nimport matplotlib.pyplot as plt\n\nfrom vectors import Vector\n\n# class SolarSystem:\n# ...\n\n# class SolarSystemBody:\n# ...\n\nclass Sun(SolarSystemBody):\n    def __init__(\n        self,\n        solar_system,\n        mass=10_000,\n        position=(0, 0, 0),\n        velocity=(0, 0, 0),\n    ):\n        super(Sun, self).__init__(solar_system, mass, position, velocity)\n        self.colour = \"yellow\"\n\nclass Planet(SolarSystemBody):\n    colours = itertools.cycle([(1, 0, 0), (0, 1, 0), (0, 0, 1)])\n\n    def __init__(\n        self,\n        solar_system,\n        mass=10,\n        position=(0, 0, 0),\n        velocity=(0, 0, 0),\n    ):\n        super(Planet, self).__init__(solar_system, mass, position, velocity)\n        self.colour = next(Planet.colours)<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>Sun<\/code> class uses a default mass of 10,000 units and sets the colour to yellow. You use the string <code>'yellow'<\/code>, which is a valid colour in Matplotlib.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the <code>Planet<\/code> class, you create an <code>itertools.cycle<\/code> object with three colours. In this case, the three colours are red, green, and blue. You can use any RGB colours you wish, and any number of colours, too. In this class, you define colours using a tuple with RGB values instead of a string with the colour name. This is also a valid way of defining colours in Matplotlib. You cycle through these colours using the <code>next()<\/code> function each time you create a new planet.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You also set the default mass to 10 units.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now, you can create a solar system with one sun and two planets in <code>simple_solar_system.py<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"3,7-21,23-24\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># simple_solar_system.py\n\nfrom solar_system_3d import SolarSystem, Sun, Planet\n\nsolar_system = SolarSystem(400)\n\nsun = Sun(solar_system)\n\nplanets = (\n    Planet(\n        solar_system,\n        position=(150, 50, 0),\n        velocity=(0, 5, 5),\n    ),\n    Planet(\n        solar_system,\n        mass=20,\n        position=(100, -50, 150),\n        velocity=(5, 0, 0)\n    )\n)\n\nwhile True:\n    solar_system.calculate_all_body_interactions()\n    solar_system.update_all()\n    solar_system.draw_all()<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this script, you create a sun and two planets. You&#8217;re assigning the sun and the planets to variables called <code>sun<\/code> and <code>planets<\/code>, but this is not strictly required as once the <code>Sun<\/code> and <code>Planet<\/code> objects are created, they&#8217;re added to <code>solar_system<\/code> and you don&#8217;t need to reference them directly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You use a <code>while<\/code> loop to run the simulation. The loop performs three operations in each iteration. When you run this script, you&#8217;ll get the following animation:<\/p>\n\n\n\n<figure class=\"wp-block-video wp-block-embed is-type-video is-provider-videopress\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"VideoPress Video Player\" aria-label='VideoPress Video Player' width='739' height='416' src='https:\/\/videopress.com\/embed\/OwuO8PcZ?cover=1&amp;preloadContent=metadata&amp;hd=0' frameborder='0' allowfullscreen data-resize-to-parent=\"true\" allow='clipboard-write'><\/iframe><script src='https:\/\/v0.wordpress.com\/js\/next\/videopress-iframe.js?m=1725245713'><\/script>\n<\/div><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">It works, sort of. You can see the sun anchored at the centre of this solar system and the planets being affected by the sun&#8217;s gravitational pull. In addition to the planets&#8217; movements in the plane containing your computer screen (these are the <em>y<\/em>&#8211; and <em>z<\/em>-axes), you can also see the planets getting larger and smaller as they also move in the <em>x<\/em>-axis, which is perpendicular to your screen.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, you may have noticed some peculiar behaviour of the planets. When they&#8217;re meant to be behind the sun, the planets are still displayed in front of the sun. This is not a problem with the mathematics\u2014if you track the positions of the planets, you&#8217;ll see that their <em>x<\/em>-coordinates show that they actually go behind the sun, as you would expect.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"showing-bodies-behind-other-bodies\">Showing bodies behind other bodies<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The issue comes from the way Matplotlib draws objects on a plot. Matplotlib plots objects in layers in the order you plot them. Since you created the sun before the planets, the <code>Sun<\/code> object comes first in <code>solar_system.bodies<\/code> and is drawn as the bottom layer. You can verify this fact by creating the sun after the planets, and you&#8217;ll see that the planets will always appear behind the sun in this case.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;d like Matplotlib to plot the solar system bodies in the correct order, starting with the ones that are the furthest back. To achieve this, you can sort the <code>SolarSystem.bodies<\/code> list based on the value of the <em>x<\/em>-coordinate each time you want to refresh the 3D plot. Here&#8217;s how you can do this in the <code>update_all()<\/code> method in <code>SolarSystem<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"13\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport itertools\nimport math\nimport matplotlib.pyplot as plt\n\nfrom vectors import Vector\n\nclass SolarSystem:\n# ...\n\n    def update_all(self):\n        self.bodies.sort(key=lambda item: item.position[0])\n        for body in self.bodies:\n            body.move()\n            body.draw()\n\n# ...\n\n# class SolarSystemBody:\n# ...\n\n# class Sun(SolarSystemBody):\n# ...\n\n# class Planet(SolarSystemBody):\n# ...<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You use the list method <code>sort<\/code> with the <code>key<\/code> parameter to define the rule you&#8217;d like to use to sort the list. The <code>lambda<\/code> function sets this rule. In this case, you&#8217;re using the value of <code>position[0]<\/code> of each body, which represents the <em>x<\/em>-coordinate. Therefore, each time you call <code>update_all()<\/code> in the simulation&#8217;s <code>while<\/code> loop, the list of bodies is reordered based on their position along the <em>x<\/em>-axis.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The result of running the <code>simple_solar_system.py<\/code> script now is the following:<\/p>\n\n\n\n<figure class=\"wp-block-video wp-block-embed is-type-video is-provider-videopress\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"VideoPress Video Player\" aria-label='VideoPress Video Player' width='739' height='416' src='https:\/\/videopress.com\/embed\/NcXqHIbk?cover=1&amp;preloadContent=metadata&amp;hd=0' frameborder='0' allowfullscreen data-resize-to-parent=\"true\" allow='clipboard-write'><\/iframe><script src='https:\/\/v0.wordpress.com\/js\/next\/videopress-iframe.js?m=1725245713'><\/script>\n<\/div><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Now, you can visualise the orbits of the planets as they orbit the sun. The changing size shows their <em>x<\/em>-position, and when the planets are behind the sun, they&#8217;re hidden from sight!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, you can also remove the axes and grid so that all you see in the simulation is the sun and the planets. You can do this by adding a call to the Matplotlib <code>axis()<\/code> method in <code>SolarSystem.draw_all()<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"16\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport itertools\nimport math\nimport matplotlib.pyplot as plt\n\nfrom vectors import Vector\n\nclass SolarSystem:\n# ...\n\n    def draw_all(self):\n        self.ax.set_xlim((-self.size \/ 2, self.size \/ 2))\n        self.ax.set_ylim((-self.size \/ 2, self.size \/ 2))\n        self.ax.set_zlim((-self.size \/ 2, self.size \/ 2))\n        self.ax.axis(False)\n        plt.pause(0.001)\n        self.ax.clear()\n\n# ...\n\n# class SolarSystemBody:\n# ...\n\n# class Sun(SolarSystemBody):\n# ...\n\n# class Planet(SolarSystemBody):\n# ...<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">And the simulation now looks like this:<\/p>\n\n\n\n<figure class=\"wp-block-video wp-block-embed is-type-video is-provider-videopress\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"VideoPress Video Player\" aria-label='VideoPress Video Player' width='739' height='416' src='https:\/\/videopress.com\/embed\/7PuQcCvs?cover=1&amp;preloadContent=metadata&amp;hd=0' frameborder='0' allowfullscreen data-resize-to-parent=\"true\" allow='clipboard-write'><\/iframe><script src='https:\/\/v0.wordpress.com\/js\/next\/videopress-iframe.js?m=1725245713'><\/script>\n<\/div><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The simulation of a 3D solar system in Python using Matplotlib is now complete. In the next section, you&#8217;ll add a feature that will allow you to view a 2D projection of the <em>xy<\/em>-plane at the bottom of the simulation. This can help with visualising the 3D dynamics of the bodies in the solar system.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"adding-a-2d-projection-of-the-xy-plane\">Adding a 2D Projection of The <em>xy<\/em>-Plane<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To help visualise the motion of the bodies in the simulation of a 3D solar system in Python, you can add a 2D projection on the &#8216;floor&#8217; of the animation. This 2D projection will show the position of the bodies in the <em>xy<\/em>-plane. To achieve this, you&#8217;ll need to add another plot to the same axes in which you&#8217;re showing the animation and only show the changes in the <em>x<\/em>&#8211; and <em>y<\/em>-coordinates. You can anchor the <em>z<\/em>-coordinate to the bottom of the plot so that the 2D projection is displayed on the floor of the animation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can start by adding a new parameter to the <code>__init__()<\/code> method for the <code>SolarSystem<\/code> class:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"10,12\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport itertools\nimport math\nimport matplotlib.pyplot as plt\n\nfrom vectors import Vector\n\nclass SolarSystem:\n    def __init__(self, size, projection_2d=False):\n        self.size = size\n        self.projection_2d = projection_2d\n        self.bodies = []\n\n        self.fig, self.ax = plt.subplots(\n            1,\n            1,\n            subplot_kw={\"projection\": \"3d\"},\n            figsize=(self.size \/ 50, self.size \/ 50),\n        )\n        self.ax.view_init(0, 0)\n        self.fig.tight_layout()\n\n# ...\n\n# class SolarSystemBody:\n# ...\n\n# class Sun(SolarSystemBody):\n# ...\n\n# class Planet(SolarSystemBody):\n# ...<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The new parameter <code>projection_2d<\/code>, which defaults to <code>False<\/code>, will allow you to toggle between the two visualisation options. If <code>projection_2d<\/code> is <code>False<\/code>, the animation will only show the bodies moving in 3D, with no axes and grid, as in the last result you&#8217;ve seen.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s start making some changes for when <code>projection_2d<\/code> is <code>True<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"22-25,40-45,92-100\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># solar_system_3d.py\n\nimport itertools\nimport math\nimport matplotlib.pyplot as plt\n\nfrom vectors import Vector\n\nclass SolarSystem:\n    def __init__(self, size, projection_2d=False):\n        self.size = size\n        self.projection_2d = projection_2d\n        self.bodies = []\n\n        self.fig, self.ax = plt.subplots(\n            1,\n            1,\n            subplot_kw={\"projection\": \"3d\"},\n            figsize=(self.size \/ 50, self.size \/ 50),\n        )\n        self.fig.tight_layout()\n        if self.projection_2d:\n            self.ax.view_init(10, 0)\n        else:\n            self.ax.view_init(0, 0)\n\n    def add_body(self, body):\n        self.bodies.append(body)\n\n    def update_all(self):\n        self.bodies.sort(key=lambda item: item.position[0])\n        for body in self.bodies:\n            body.move()\n            body.draw()\n\n    def draw_all(self):\n        self.ax.set_xlim((-self.size \/ 2, self.size \/ 2))\n        self.ax.set_ylim((-self.size \/ 2, self.size \/ 2))\n        self.ax.set_zlim((-self.size \/ 2, self.size \/ 2))\n        if self.projection_2d:\n            self.ax.xaxis.set_ticklabels([])\n            self.ax.yaxis.set_ticklabels([])\n            self.ax.zaxis.set_ticklabels([])\n        else:\n            self.ax.axis(False)\n        plt.pause(0.001)\n        self.ax.clear()\n\n    def calculate_all_body_interactions(self):\n        bodies_copy = self.bodies.copy()\n        for idx, first in enumerate(bodies_copy):\n            for second in bodies_copy[idx + 1:]:\n                first.accelerate_due_to_gravity(second)\n\nclass SolarSystemBody:\n    min_display_size = 10\n    display_log_base = 1.3\n\n    def __init__(\n        self,\n        solar_system,\n        mass,\n        position=(0, 0, 0),\n        velocity=(0, 0, 0),\n    ):\n        self.solar_system = solar_system\n        self.mass = mass\n        self.position = position\n        self.velocity = Vector(*velocity)\n        self.display_size = max(\n            math.log(self.mass, self.display_log_base),\n            self.min_display_size,\n        )\n        self.colour = \"black\"\n\n        self.solar_system.add_body(self)\n\n    def move(self):\n        self.position = (\n            self.position[0] + self.velocity[0],\n            self.position[1] + self.velocity[1],\n            self.position[2] + self.velocity[2],\n        )\n\n    def draw(self):\n        self.solar_system.ax.plot(\n            *self.position,\n            marker=\"o\",\n            markersize=self.display_size + self.position[0] \/ 30,\n            color=self.colour\n        )\n        if self.solar_system.projection_2d:\n            self.solar_system.ax.plot(\n                self.position[0],\n                self.position[1],\n                -self.solar_system.size \/ 2,\n                marker=\"o\",\n                markersize=self.display_size \/ 2,\n                color=(.5, .5, .5),\n            )\n\n    def accelerate_due_to_gravity(self, other):\n        distance = Vector(*other.position) - Vector(*self.position)\n        distance_mag = distance.get_magnitude()\n\n        force_mag = self.mass * other.mass \/ (distance_mag ** 2)\n        force = distance.normalize() * force_mag\n\n        reverse = 1\n        for body in self, other:\n            acceleration = force \/ body.mass\n            body.velocity += acceleration * reverse\n            reverse = -1\n\nclass Sun(SolarSystemBody):\n    def __init__(\n        self,\n        solar_system,\n        mass=10_000,\n        position=(0, 0, 0),\n        velocity=(0, 0, 0),\n    ):\n        super(Sun, self).__init__(solar_system, mass, position, velocity)\n        self.colour = \"yellow\"\n\nclass Planet(SolarSystemBody):\n    colours = itertools.cycle([(1, 0, 0), (0, 1, 0), (0, 0, 1)])\n\n    def __init__(\n        self,\n        solar_system,\n        mass=10,\n        position=(0, 0, 0),\n        velocity=(0, 0, 0),\n    ):\n        super(Planet, self).__init__(solar_system, mass, position, velocity)\n        self.colour = next(Planet.colours)<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The changes you&#8217;ve made are the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In <code>SolarSystem.__init__()<\/code>, the 3D view is set to <code>view_init(0, 0)<\/code> when the 2D projection is turned off, as before. However, the elevation is changed to 10\u00ba when the 2D projection option is turned on to allow the bottom plane to be visible.<\/li>\n\n\n\n<li>In <code>SolarSystem.draw_all()<\/code>, the grid and axes are turned off only when there is no 2D projection. When the 2D projection is enabled, the axes and grid are displayed. However, the tick marks are replaced with blanks since the numbers on the three axes are arbitrary and are not needed.<\/li>\n\n\n\n<li>In <code>SolarSystemBody.draw()<\/code>, a second plot is added when <code>projection_2d<\/code> is <code>True<\/code>. The first two arguments in <code>plot()<\/code> are the bodies&#8217; <em>x<\/em>&#8211; and <em>y<\/em>-positions. However, instead of using the <em>z<\/em>-position as the third argument, you use the minimum value of <em>z<\/em> which represents the &#8216;floor&#8217; of the cube containting the three axes. You then plot a grey marker half the size of the main markers in the animation.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll also need to make a small change in <code>simple_solar_system.py<\/code> to turn on the 2D projection:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"5\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># simple_solar_system.py\n\nfrom solar_system_3d import SolarSystem, Sun, Planet\n\nsolar_system = SolarSystem(400, projection_2d=True)\n\nsun = Sun(solar_system)\n\nplanets = (\n    Planet(\n        solar_system,\n        position=(150, 50, 0),\n        velocity=(0, 5, 5),\n    ),\n    Planet(\n        solar_system,\n        mass=20,\n        position=(100, -50, 150),\n        velocity=(5, 0, 0)\n    )\n)\n\nwhile True:\n    solar_system.calculate_all_body_interactions()\n    solar_system.update_all()\n    solar_system.draw_all()<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The simulation now looks like this:<\/p>\n\n\n\n<figure class=\"wp-block-video wp-block-embed is-type-video is-provider-videopress\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"VideoPress Video Player\" aria-label='VideoPress Video Player' width='739' height='416' src='https:\/\/videopress.com\/embed\/LBcxyYKk?cover=1&amp;preloadContent=metadata&amp;hd=0' frameborder='0' allowfullscreen data-resize-to-parent=\"true\" allow='clipboard-write'><\/iframe><script src='https:\/\/v0.wordpress.com\/js\/next\/videopress-iframe.js?m=1725245713'><\/script>\n<\/div><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The 2D projection of the <em>xy<\/em>-plane makes it easier to follow the paths of the orbiting bodies.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"creating-a-binary-star-system\">Creating a Binary Star System<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll finish off with another simulation of a 3D solar system in Python. You&#8217;ll simulate a binary star system using the same classes you&#8217;ve already defined. Create a new file called <code>binary_star_system.py<\/code> and create two suns and two planets:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># binary_star_system.py\n\nfrom solar_system_3d import SolarSystem, Sun, Planet\n\nsolar_system = SolarSystem(400)\n\nsuns = (\n    Sun(solar_system, position=(40, 40, 40), velocity=(6, 0, 6)),\n    Sun(solar_system, position=(-40, -40, 40), velocity=(-6, 0, -6)),\n)\n\nplanets = (\n    Planet(\n        solar_system,\n        10,\n        position=(100, 100, 0),\n        velocity=(0, 5.5, 5.5),\n    ),\n    Planet(\n        solar_system,\n        20,\n        position=(0, 0, 0),\n        velocity=(-11, 11, 0),\n    ),\n)\n\nwhile True:\n    solar_system.calculate_all_body_interactions()\n    solar_system.update_all()\n    solar_system.draw_all()<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The simulation of this binary star system is the following:<\/p>\n\n\n\n<figure class=\"wp-block-video wp-block-embed is-type-video is-provider-videopress\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"VideoPress Video Player\" aria-label='VideoPress Video Player' width='739' height='416' src='https:\/\/videopress.com\/embed\/jpHRWIKG?cover=1&amp;preloadContent=metadata&amp;hd=0' frameborder='0' allowfullscreen data-resize-to-parent=\"true\" allow='clipboard-write'><\/iframe><script src='https:\/\/v0.wordpress.com\/js\/next\/videopress-iframe.js?m=1725245713'><\/script>\n<\/div><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Or you can turn on the 2D projection when creating the <code>SolarSystem<\/code> object:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"5\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># binary_star_system.py\n\nfrom solar_system_3d import SolarSystem, Sun, Planet\n\nsolar_system = SolarSystem(400, projection_2d=True)\n\n# ...<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This version gives the following result:<\/p>\n\n\n\n<figure class=\"wp-block-video wp-block-embed is-type-video is-provider-videopress\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"VideoPress Video Player\" aria-label='VideoPress Video Player' width='739' height='416' src='https:\/\/videopress.com\/embed\/zI2ZCPux?cover=1&amp;preloadContent=metadata&amp;hd=0' frameborder='0' allowfullscreen data-resize-to-parent=\"true\" allow='clipboard-write'><\/iframe><script src='https:\/\/v0.wordpress.com\/js\/next\/videopress-iframe.js?m=1725245713'><\/script>\n<\/div><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">This binary star system is not stable, and both planets are soon flung out of the system by the two suns!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you wish, you can extend the class definitions to detect collisions between two bodies and remove a planet if it collides with a sun. The simpler, 2D version of this project, which <a href=\"https:\/\/thepythoncodingbook.com\/2021\/09\/29\/simulating-orbiting-planets-in-a-solar-system-using-python-orbiting-planets-series-1\/\">simulates orbiting planets in 2D<\/a>, includes this feature. You can look at how it was implemented in that simpler project if you&#8217;d like to add it to this project.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>The final versions of the code used in this article are also <a href=\"https:\/\/github.com\/codetoday-london\/simulation-3d-solar-system-in-python-using-matplotlib.git\">available on this GitHub repo<\/a>.<\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"final-words\">Final Words<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You can now simulate a 3D solar system in Python using Matplotlib. In this article, you&#8217;ve learned how to place objects in 3D space using vectors and the graphical capabilities of Matplotlib. You can read more about how to use Matplotlib, including making more complex animations using the <code>animations<\/code> submodule in Matplotlib, in the Chapter <a href=\"https:\/\/thepythoncodingbook.com\/basics-of-data-visualisation-in-python-using-matplotlib\/\">Basics of Data Visualisation in Python Using Matplotlib<\/a> of The Python Coding Book.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This completes the two-part Orbiting Planets Series. In the first post of the series, <a href=\"https:\/\/thepythoncodingbook.com\/2021\/09\/29\/simulating-orbiting-planets-in-a-solar-system-using-python-orbiting-planets-series-1\/\">you considered only the 2D scenario and used the <code>turtle<\/code> module to create the graphical animation<\/a>. In the second article, the one you just finished, you looked at a 3D solar system in Python using Matplotlib for the graphical representation of the animation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It&#8217;s now your turn to try and create simple and more complex solar systems. Can you create a stable binary star system?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I hope you enjoyed simulating a 3D solar system in Python using Matplotlib. Now you&#8217;re ready to try and create your own simulations of real-world processes.<\/p>\n\n\n\n<div class=\"wp-block-group alignfull\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-group alignfull\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-coblocks-hero alignfull coblocks-hero-230194844519\"><div class=\"wp-block-coblocks-hero__inner has-background hero-center-left-align has-padding has-huge-padding\" style=\"background-color:#fff3e6;min-height:500px\"><div class=\"wp-block-coblocks-hero__content-wrapper\"><div class=\"wp-block-coblocks-hero__content\" style=\"max-width:560px\">\n<h2 class=\"wp-block-heading\">Subscribe to<\/h2>\n\n\n\n<h2 class=\"wp-block-heading\">The Python Coding Stack<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Regular articles for the intermediate Python programmer or a beginner who wants to &#8220;read ahead&#8221;<\/p>\n\n\n\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-50\"><a class=\"wp-block-button__link has-black-color has-text-color has-background wp-element-button\" href=\"https:\/\/thepythoncodingstack.substack.com\" style=\"background-color:#fdb33b\">Subscribe<\/a><\/div>\n<\/div>\n<\/div><\/div><\/div><\/div>\n<\/div><\/div>\n<\/div><\/div>\n\n\n\n<div style=\"height:30px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"further-reading\">Further Reading<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>You can read the first article in this series which <a href=\"https:\/\/thepythoncodingbook.com\/2021\/09\/29\/simulating-orbiting-planets-in-a-solar-system-using-python-orbiting-planets-series-1\/\">simulates orbiting planets in 2D<\/a> using the <code>turtle<\/code> graphics module<\/li>\n\n\n\n<li>Read more about <a href=\"https:\/\/thepythoncodingbook.com\/object-oriented-programming\/\">object-oriented programming<\/a><\/li>\n\n\n\n<li>You may find this article about using the <a href=\"https:\/\/thepythoncodingbook.com\/2021\/08\/30\/2d-fourier-transform-in-python-and-fourier-synthesis-of-images\/\">2D Fourier Transform in Python<\/a> to reconstruct images from sine functions of interest, too<\/li>\n\n\n\n<li>Finally, if you want to get a different type of understanding of what happens behind the scenes in a Python program, try <a href=\"https:\/\/thepythoncodingbook.com\/understanding-programming-the-white-room\/\">The White Room: Understanding Programming<\/a><\/li>\n<\/ul>\n\n\n\n<div style=\"height:30px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<div class=\"wp-block-group\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-group alignfull\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-group alignfull\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-coblocks-hero alignfull coblocks-hero-230194844519\"><div class=\"wp-block-coblocks-hero__inner has-background hero-center-left-align has-padding has-huge-padding\" style=\"background-color:#1a6b72;min-height:500px\"><div class=\"wp-block-coblocks-hero__content-wrapper\"><div class=\"wp-block-coblocks-hero__content\" style=\"max-width:560px\">\n<h2 class=\"wp-block-heading has-text-color has-link-color wp-elements-806dd89de56256fb948e5020de497de4\" style=\"color:#fff3e6\">Become a Member of<\/h2>\n\n\n\n<h2 class=\"wp-block-heading has-text-color has-link-color wp-elements-7d78fcf199c064aa3173690e46837383\" style=\"color:#fff3e6\">The Python Coding Place<\/h2>\n\n\n\n<p class=\"has-text-color has-link-color wp-elements-57091ca0dd26b2b579f184ab1723dc89 wp-block-paragraph\" style=\"color:#fff3e6\">Video courses, live cohort-based courses, workshops, weekly videos, members&#8217; forum, and more\u2026<\/p>\n\n\n\n<div style=\"height:66px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-50\"><a class=\"wp-block-button__link has-black-color has-text-color has-background wp-element-button\" href=\"https:\/\/thepythoncodingplace.com\" style=\"background-color:#fdb33b\">Become a Member<\/a><\/div>\n<\/div>\n<\/div><\/div><\/div><\/div>\n<\/div><\/div>\n<\/div><\/div>\n<\/div><\/div>\n\n\n\n<div class=\"wp-block-group\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<div style=\"height:30px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<div class=\"wp-block-group\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<hr class=\"wp-block-separator has-css-opacity is-style-wide\"\/>\n\n\n\n<div class=\"wp-block-group alignfull\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-group alignfull\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<div class=\"wp-block-coblocks-hero alignfull coblocks-hero-230194844519\"><div class=\"wp-block-coblocks-hero__inner has-background hero-center-left-align has-padding has-huge-padding\" style=\"background-color:#fff3e6;min-height:500px\"><div class=\"wp-block-coblocks-hero__content-wrapper\"><div class=\"wp-block-coblocks-hero__content\" style=\"max-width:560px\">\n<h2 class=\"wp-block-heading\">Subscribe to<\/h2>\n\n\n\n<h2 class=\"wp-block-heading\">The Python Coding Stack<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Regular articles for the intermediate Python programmer or a beginner who wants to &#8220;read ahead&#8221;<\/p>\n\n\n\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-50\"><a class=\"wp-block-button__link has-black-color has-text-color has-background wp-element-button\" href=\"https:\/\/thepythoncodingstack.substack.com\" style=\"background-color:#fdb33b\">Subscribe<\/a><\/div>\n<\/div>\n<\/div><\/div><\/div><\/div>\n<\/div><\/div>\n<\/div><\/div>\n\n\n\n<ul class=\"wp-block-social-links is-style-default is-layout-flex wp-block-social-links-is-layout-flex\"><li class=\"wp-social-link wp-social-link-twitter wp-block-social-link\"><a href=\"https:\/\/twitter.com\/s_gruppetta_ct\" class=\"wp-block-social-link-anchor\"><svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" version=\"1.1\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M22.23,5.924c-0.736,0.326-1.527,0.547-2.357,0.646c0.847-0.508,1.498-1.312,1.804-2.27 c-0.793,0.47-1.671,0.812-2.606,0.996C18.324,4.498,17.257,4,16.077,4c-2.266,0-4.103,1.837-4.103,4.103 c0,0.322,0.036,0.635,0.106,0.935C8.67,8.867,5.647,7.234,3.623,4.751C3.27,5.357,3.067,6.062,3.067,6.814 c0,1.424,0.724,2.679,1.825,3.415c-0.673-0.021-1.305-0.206-1.859-0.513c0,0.017,0,0.034,0,0.052c0,1.988,1.414,3.647,3.292,4.023 c-0.344,0.094-0.707,0.144-1.081,0.144c-0.264,0-0.521-0.026-0.772-0.074c0.522,1.63,2.038,2.816,3.833,2.85 c-1.404,1.1-3.174,1.756-5.096,1.756c-0.331,0-0.658-0.019-0.979-0.057c1.816,1.164,3.973,1.843,6.29,1.843 c7.547,0,11.675-6.252,11.675-11.675c0-0.178-0.004-0.355-0.012-0.531C20.985,7.47,21.68,6.747,22.23,5.924z\"><\/path><\/svg><span class=\"wp-block-social-link-label screen-reader-text\">Twitter<\/span><\/a><\/li>\n\n<li class=\"wp-social-link wp-social-link-linkedin wp-block-social-link\"><a href=\"https:\/\/www.linkedin.com\/in\/stephengruppetta\/\" class=\"wp-block-social-link-anchor\"><svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" version=\"1.1\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M19.7,3H4.3C3.582,3,3,3.582,3,4.3v15.4C3,20.418,3.582,21,4.3,21h15.4c0.718,0,1.3-0.582,1.3-1.3V4.3 C21,3.582,20.418,3,19.7,3z M8.339,18.338H5.667v-8.59h2.672V18.338z M7.004,8.574c-0.857,0-1.549-0.694-1.549-1.548 c0-0.855,0.691-1.548,1.549-1.548c0.854,0,1.547,0.694,1.547,1.548C8.551,7.881,7.858,8.574,7.004,8.574z M18.339,18.338h-2.669 v-4.177c0-0.996-0.017-2.278-1.387-2.278c-1.389,0-1.601,1.086-1.601,2.206v4.249h-2.667v-8.59h2.559v1.174h0.037 c0.356-0.675,1.227-1.387,2.526-1.387c2.703,0,3.203,1.779,3.203,4.092V18.338z\"><\/path><\/svg><span class=\"wp-block-social-link-label screen-reader-text\">LinkedIn<\/span><\/a><\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-css-opacity is-style-wide\"\/>\n<\/div><\/div>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>One of the uses of programming is to help us understand the real world through simulation. This technique is used in science, finance, and many other quantitative fields. As long as the &#8220;rules&#8221; which govern the real-world properties are known, you can write a computer program that explores the outcomes you get from following those&hellip; <a class=\"more-link\" href=\"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/\">Continue reading <span class=\"screen-reader-text\">Simulating a 3D Solar System In Python Using Matplotlib (Orbiting Planets Series #2)<\/span> <span class=\"meta-nav\" aria-hidden=\"true\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":192321682,"featured_media":1840,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_coblocks_attr":"","_coblocks_dimensions":"","_coblocks_responsive_height":"","_coblocks_accordion_ie_support":"","_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_wpcom_ai_launchpad_first_post":false,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"Just published: Simulating a 3D Solar System in #Python using #Matplotlib\n\nThe Axes3D object in @matplotlib provides the infrastructure to create the solar system. Physics does the rest...\n\n#coding #programming","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"_wpas_customize_per_network":false,"jetpack_post_was_ever_published":false},"categories":[1372],"tags":[1363,1377,1364,1383],"class_list":["post-1801","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-beyond-beginners","tag-beyond-beginners","tag-object-oriented-programming","tag-python","tag-simulation"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Simulating a 3D Solar System In Python Using Matplotlib<\/title>\n<meta name=\"description\" content=\"Simulating a 3D Solar System in Python using Matplotlib. Explore how to represent a 3D real-world system in Python\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/\" \/>\n<meta property=\"og:locale\" content=\"en_GB\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Simulating a 3D Solar System In Python Using Matplotlib\" \/>\n<meta property=\"og:description\" content=\"Simulating a 3D Solar System in Python using Matplotlib. Explore how to represent a 3D real-world system in Python\" \/>\n<meta property=\"og:url\" content=\"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/\" \/>\n<meta property=\"og:site_name\" content=\"The Python Coding Book\" \/>\n<meta property=\"article:published_time\" content=\"2021-12-11T19:39:56+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-11-12T11:36:18+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/planets-gc8e1ee79a_1920.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1920\" \/>\n\t<meta property=\"og:image:height\" content=\"720\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Stephen Gruppetta\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Stephen Gruppetta\" \/>\n\t<meta name=\"twitter:label2\" content=\"Estimated reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"24 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/\"},\"author\":{\"name\":\"Stephen Gruppetta\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#\\\/schema\\\/person\\\/3e2577e1f4cdec0363274e7b084e0493\"},\"headline\":\"Simulating a 3D Solar System In Python Using Matplotlib (Orbiting Planets Series #2)\",\"datePublished\":\"2021-12-11T19:39:56+00:00\",\"dateModified\":\"2023-11-12T11:36:18+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/\"},\"wordCount\":5613,\"commentCount\":35,\"publisher\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/i0.wp.com\\\/thepythoncodingbook.com\\\/wp-content\\\/uploads\\\/2021\\\/12\\\/planets-gc8e1ee79a_1920.jpg?fit=1920%2C720&ssl=1\",\"keywords\":[\"Beyond Beginners\",\"object-oriented programming\",\"python\",\"simulation\"],\"articleSection\":[\"Beyond Beginners\"],\"inLanguage\":\"en-GB\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/\",\"url\":\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/\",\"name\":\"Simulating a 3D Solar System In Python Using Matplotlib\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/i0.wp.com\\\/thepythoncodingbook.com\\\/wp-content\\\/uploads\\\/2021\\\/12\\\/planets-gc8e1ee79a_1920.jpg?fit=1920%2C720&ssl=1\",\"datePublished\":\"2021-12-11T19:39:56+00:00\",\"dateModified\":\"2023-11-12T11:36:18+00:00\",\"description\":\"Simulating a 3D Solar System in Python using Matplotlib. Explore how to represent a 3D real-world system in Python\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/#breadcrumb\"},\"inLanguage\":\"en-GB\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-GB\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/#primaryimage\",\"url\":\"https:\\\/\\\/i0.wp.com\\\/thepythoncodingbook.com\\\/wp-content\\\/uploads\\\/2021\\\/12\\\/planets-gc8e1ee79a_1920.jpg?fit=1920%2C720&ssl=1\",\"contentUrl\":\"https:\\\/\\\/i0.wp.com\\\/thepythoncodingbook.com\\\/wp-content\\\/uploads\\\/2021\\\/12\\\/planets-gc8e1ee79a_1920.jpg?fit=1920%2C720&ssl=1\",\"width\":1920,\"height\":720},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/2021\\\/12\\\/11\\\/simulating-3d-solar-system-python-matplotlib\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/thepythoncodingbook.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Simulating a 3D Solar System In Python Using Matplotlib (Orbiting Planets Series #2)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#website\",\"url\":\"https:\\\/\\\/thepythoncodingbook.com\\\/\",\"name\":\"The Python Coding Book\",\"description\":\"The friendly, relaxed programming book\",\"publisher\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/thepythoncodingbook.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-GB\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#organization\",\"name\":\"Codetoday\",\"url\":\"https:\\\/\\\/thepythoncodingbook.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-GB\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/i0.wp.com\\\/thepythoncodingbook.com\\\/wp-content\\\/uploads\\\/2021\\\/04\\\/cropped-icon-only.png?fit=512%2C512&ssl=1\",\"contentUrl\":\"https:\\\/\\\/i0.wp.com\\\/thepythoncodingbook.com\\\/wp-content\\\/uploads\\\/2021\\\/04\\\/cropped-icon-only.png?fit=512%2C512&ssl=1\",\"width\":512,\"height\":512,\"caption\":\"Codetoday\"},\"image\":{\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/thepythoncodingbook.com\\\/#\\\/schema\\\/person\\\/3e2577e1f4cdec0363274e7b084e0493\",\"name\":\"Stephen Gruppetta\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-GB\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/835a0f5c56d81762310449d7d198694c621ca67f7b53ac17c3baaf9041784c93?s=96&d=identicon&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/835a0f5c56d81762310449d7d198694c621ca67f7b53ac17c3baaf9041784c93?s=96&d=identicon&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/835a0f5c56d81762310449d7d198694c621ca67f7b53ac17c3baaf9041784c93?s=96&d=identicon&r=g\",\"caption\":\"Stephen Gruppetta\"},\"sameAs\":[\"http:\\\/\\\/thepythoncodingbook.wordpress.com\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Simulating a 3D Solar System In Python Using Matplotlib","description":"Simulating a 3D Solar System in Python using Matplotlib. Explore how to represent a 3D real-world system in Python","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/","og_locale":"en_GB","og_type":"article","og_title":"Simulating a 3D Solar System In Python Using Matplotlib","og_description":"Simulating a 3D Solar System in Python using Matplotlib. Explore how to represent a 3D real-world system in Python","og_url":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/","og_site_name":"The Python Coding Book","article_published_time":"2021-12-11T19:39:56+00:00","article_modified_time":"2023-11-12T11:36:18+00:00","og_image":[{"width":1920,"height":720,"url":"https:\/\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/planets-gc8e1ee79a_1920.jpg","type":"image\/jpeg"}],"author":"Stephen Gruppetta","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Stephen Gruppetta","Estimated reading time":"24 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/#article","isPartOf":{"@id":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/"},"author":{"name":"Stephen Gruppetta","@id":"https:\/\/thepythoncodingbook.com\/#\/schema\/person\/3e2577e1f4cdec0363274e7b084e0493"},"headline":"Simulating a 3D Solar System In Python Using Matplotlib (Orbiting Planets Series #2)","datePublished":"2021-12-11T19:39:56+00:00","dateModified":"2023-11-12T11:36:18+00:00","mainEntityOfPage":{"@id":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/"},"wordCount":5613,"commentCount":35,"publisher":{"@id":"https:\/\/thepythoncodingbook.com\/#organization"},"image":{"@id":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/#primaryimage"},"thumbnailUrl":"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/planets-gc8e1ee79a_1920.jpg?fit=1920%2C720&ssl=1","keywords":["Beyond Beginners","object-oriented programming","python","simulation"],"articleSection":["Beyond Beginners"],"inLanguage":"en-GB","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/","url":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/","name":"Simulating a 3D Solar System In Python Using Matplotlib","isPartOf":{"@id":"https:\/\/thepythoncodingbook.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/#primaryimage"},"image":{"@id":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/#primaryimage"},"thumbnailUrl":"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/planets-gc8e1ee79a_1920.jpg?fit=1920%2C720&ssl=1","datePublished":"2021-12-11T19:39:56+00:00","dateModified":"2023-11-12T11:36:18+00:00","description":"Simulating a 3D Solar System in Python using Matplotlib. Explore how to represent a 3D real-world system in Python","breadcrumb":{"@id":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/#breadcrumb"},"inLanguage":"en-GB","potentialAction":[{"@type":"ReadAction","target":["https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/"]}]},{"@type":"ImageObject","inLanguage":"en-GB","@id":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/#primaryimage","url":"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/planets-gc8e1ee79a_1920.jpg?fit=1920%2C720&ssl=1","contentUrl":"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/planets-gc8e1ee79a_1920.jpg?fit=1920%2C720&ssl=1","width":1920,"height":720},{"@type":"BreadcrumbList","@id":"https:\/\/thepythoncodingbook.com\/2021\/12\/11\/simulating-3d-solar-system-python-matplotlib\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/thepythoncodingbook.com\/"},{"@type":"ListItem","position":2,"name":"Simulating a 3D Solar System In Python Using Matplotlib (Orbiting Planets Series #2)"}]},{"@type":"WebSite","@id":"https:\/\/thepythoncodingbook.com\/#website","url":"https:\/\/thepythoncodingbook.com\/","name":"The Python Coding Book","description":"The friendly, relaxed programming book","publisher":{"@id":"https:\/\/thepythoncodingbook.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/thepythoncodingbook.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-GB"},{"@type":"Organization","@id":"https:\/\/thepythoncodingbook.com\/#organization","name":"Codetoday","url":"https:\/\/thepythoncodingbook.com\/","logo":{"@type":"ImageObject","inLanguage":"en-GB","@id":"https:\/\/thepythoncodingbook.com\/#\/schema\/logo\/image\/","url":"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/04\/cropped-icon-only.png?fit=512%2C512&ssl=1","contentUrl":"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/04\/cropped-icon-only.png?fit=512%2C512&ssl=1","width":512,"height":512,"caption":"Codetoday"},"image":{"@id":"https:\/\/thepythoncodingbook.com\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/thepythoncodingbook.com\/#\/schema\/person\/3e2577e1f4cdec0363274e7b084e0493","name":"Stephen Gruppetta","image":{"@type":"ImageObject","inLanguage":"en-GB","@id":"https:\/\/secure.gravatar.com\/avatar\/835a0f5c56d81762310449d7d198694c621ca67f7b53ac17c3baaf9041784c93?s=96&d=identicon&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/835a0f5c56d81762310449d7d198694c621ca67f7b53ac17c3baaf9041784c93?s=96&d=identicon&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/835a0f5c56d81762310449d7d198694c621ca67f7b53ac17c3baaf9041784c93?s=96&d=identicon&r=g","caption":"Stephen Gruppetta"},"sameAs":["http:\/\/thepythoncodingbook.wordpress.com"]}]}},"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/thepythoncodingbook.com\/wp-content\/uploads\/2021\/12\/planets-gc8e1ee79a_1920.jpg?fit=1920%2C720&ssl=1","jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pd1Q8F-t3","_links":{"self":[{"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/posts\/1801","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/users\/192321682"}],"replies":[{"embeddable":true,"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/comments?post=1801"}],"version-history":[{"count":23,"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/posts\/1801\/revisions"}],"predecessor-version":[{"id":3764,"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/posts\/1801\/revisions\/3764"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/media\/1840"}],"wp:attachment":[{"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/media?parent=1801"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/categories?post=1801"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thepythoncodingbook.com\/wp-json\/wp\/v2\/tags?post=1801"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}