Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Matplotlib 3D Plot Advanced

#1
Matplotlib 3D Plot Advanced

<div><p>If you’ve already learned how to make <a href="https://blog.finxter.com/matplotlib-3d-plot/" target="_blank" rel="noreferrer noopener">basic 3d plots in maptlotlib</a> and want to take them to the next level, then look no further. In this article, I’ll teach you how to create the two most common 3D plots (surface and wireframe plots) and a step-by-step method you can use to create any shape you can imagine.</p>
<p>In addition to <code>import matplotlib.pyplot as plt</code> and calling <code>plt.show()</code>, to create a 3D plot in matplotlib, you need to:</p>
<ol>
<li>Import the <code>Axes3D</code> object</li>
<li>Initialize your <code>Figure</code> and <code>Axes3D</code> object</li>
<li>Get some 3D data</li>
<li>Plot it using <code>Axes</code> notation</li>
</ol>
<p>Here’s a wireframe plot: </p>
<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=""># Standard import
import matplotlib.pyplot as plt # Import 3D Axes
from mpl_toolkits.mplot3d import axes3d # Set up Figure and 3D Axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Get some data
X, Y, Z = axes3d.get_test_data(0.1) # Plot using Axes notation
ax.plot_wireframe(X, Y, Z)
plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img0.png" alt=""/></figure>
<p><strong>Try It Yourself on our interactive Python shell (and check out the file <code>'plot.png'</code>):</strong></p>
<p> <iframe height="700px" width="100%" src="https://repl.it/@finxter/matplotlibarticle3dplot?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p>
<p>Changing the plot call to <code>ax.plot_surface(X, Y, Z)</code> gives</p>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img1.png" alt=""/></figure>
<p>Great! You’ve just created your first 3D wireframe and surface plots. Don’t worry if that was a bit fast; let’s dive into a more detailed example.</p>
<p>But first, note that your plots may look different to mine because I use the seaborn style throughout. You can set this by installing the seaborn library and calling the set function at the top of your code.</p>
<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 seaborn as sns; sns.set()</pre>
<h2>Matplotlib 3D Plot Example</h2>
<p>The four steps needed to create advanced 3D plots are the same as those needed to create basic ones. If you don’t understand those steps, check out my article on how to make <a href="https://blog.finxter.com/matplotlib-3d-plot/">basic 3D plots</a> first.</p>
<p>The most difficult part of creating surface and wireframe plots is step 3: getting 3D data. Matplotlib actually includes a helper function <code>axes3d.get_test_data()</code> to generate some data for you. It accepts a float and, for best results, choose a value between 0 and 1. It always produces the same plot, but different floats give you different sized data and thus impact how detailed the plot is.</p>
<p>However, the best way to learn 3D plotting is to create custom plots.</p>
<p>At the end of step 3, you want to have three <a href="https://blog.finxter.com/what-are-advantages-of-numpy-over-regular-python-lists/" target="_blank" rel="noreferrer noopener">numpy arrays</a> <code>X</code>, <code>Y</code> and <code>Z</code>, which you will pass to <code>ax.plot_wireframe()</code> or <code>ax.plot_surface()</code>. You can break step 3 down into four steps:</p>
<ol>
<li>Define the x-axis and y-axis limits</li>
<li>Create a grid of XY-points (to get X and Y)</li>
<li>Define a z-function</li>
<li>Apply the z-function to X and Y (to get Z)</li>
</ol>
<p>In matplotlib, the z-axis is vertical by default. So, the ‘bottom’ of the <code>Axes3D</code> object is a grid of XY points. For surface or wireframe plots, each pair of XY points has a corresponding Z value. So, we can think of surface/wireframe plots as the result of applying some z-function to every XY-pair on the ‘bottom’ of the <code>Axes3D</code> object.</p>
<p>Since there are infinitely many numbers on the XY-plane, it is not possible to map every one to a Z-value. You just need an amount large enough to deceive humans – anything above 50 pairs usually works well.</p>
<p>To create your XY-points, you first need to define the x-axis and y-axis limits. Let’s say you want X-values ranging from -5 to +5 and Y-values from -2 to +2. You can create an array of numbers for each of these using the <a href="https://blog.finxter.com/np-linspace/"><code>np.linspace()</code></a> function. For reasons that will become clear later, I will make <code>x</code> have 100 points, and <code>y</code> have 70. </p>
<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="">x = np.linspace(-5, 5, num=100)
y = np.linspace(-2, 2, num=70)
</pre>
<p>Both <code>x</code> and <code>y</code> are 1D arrays containing <code>num</code> equally spaced floats in the ranges <code>[-5, 5]</code> and <code>[-2, 2]</code> respectively.</p>
<p>Since the XY-plane is a 2D object, you now need to create a rectangular grid of all xy-pairs. To do this, use the <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener">numpy </a>function <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html"><code>np.meshgrid()</code></a>. It takes <code>n</code> 1D arrays and turns them into an N-dimensional grid. In this case, it takes two 1D arrays and turns them into a 2D grid. </p>
<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="">X, Y = np.meshgrid(x, y)
</pre>
<p>Now you’ve created <code>X</code> and <code>Y</code>, so let’s inspect them.</p>
<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="">print(f'Type of X: {type(X)}')
print(f'Shape of X: {X.shape}\n')
print(f'Type of Y: {type(Y)}')
print(f'Shape of Y: {Y.shape}')
</pre>
<pre class="wp-block-preformatted">Type of X: &lt;class 'numpy.ndarray'&gt;
Shape of X: (70, 100) Type of Y: &lt;class 'numpy.ndarray'&gt;
Shape of Y: (70, 100)
</pre>
<p>Both <code>X</code> and <code>Y</code> are numpy arrays of the same shape: <code>(70, 100)</code>. This corresponds to the size of <code>y</code> and <code>x</code> respectively. As you would expect, the size of <code>y</code> dictates the height of the array, i.e., the number of rows and the size of <code>x</code> dictates the width, i.e., the number of columns.</p>
<p>Note that I used lowercase <code>x</code> and <code>y</code> for the 1D arrays and uppercase <code>X</code> and <code>Y</code> for the 2D arrays. This is standard practice when making 3D plots, and I use it throughout the article.</p>
<p>Now you’ve created your grid of points; it’s time to define a function to apply to them all. Since this function outputs z-values, I call it a z-function. <a href="https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html">Common z-functions</a> contain <code>np.sin()</code> and <code>np.cos()</code> because they create repeating, cyclical patterns that look interesting when plotted in 3D. Additionally, z-functions usually combine both <code>X</code> and <code>Y</code> variables as 3D plots look at how all the variables interact. </p>
<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=""># Define z-function with 2 arguments: x and y
def z_func(x, y): return np.sin(np.cos(x) + y) # Apply to X and Y
Z = z_func(X, Y)
</pre>
<p>Here I defined a z-function that accepts 2 variables – <code>x</code> and <code>y</code> – and is a combination of <code>np.sin()</code> and <code>np.cos()</code> functions. Then I applied it to <code>X</code> and <code>Y</code> to get the <code>Z</code> array. Thanks to <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html">numpy broadcasting</a>, python applies the z-function to every XY pair almost instantly and saves you from having to write a wildly inefficient <code>for</code> loop.</p>
<p>Note that <code>Z</code> is the same shape and type as both <code>X</code> and <code>Y</code>. </p>
<pre class="wp-block-preformatted">print(f'Type of Z: <strong>{</strong>type(Z)<strong>}</strong>')
print(f'Shape of Z: <strong>{</strong>Z.shape<strong>}</strong>')
</pre>
<pre class="wp-block-preformatted">Type of Z: &lt;class 'numpy.ndarray'&gt;
Shape of Z: (70, 100)
</pre>
<p>Now that you have got your data, all that is left to do is make the plots. Let’s put all the above code together: </p>
<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=""># Set up Figure and 3D Axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Create x and y 1D arrays
x = np.linspace(-5, 5, num=100)
y = np.linspace(-2, 2, num=70) # Create X and Y 2D arrays
X, Y = np.meshgrid(x, y) # Define Z-function
def z_func(x, y): return np.sin(np.cos(x) + y) # Create Z 2D array
Z = z_func(X, Y) # Plot using Axes notation
ax.plot_wireframe(X, Y, Z)
# Set axes lables
ax.set(xlabel='x', ylabel='y', zlabel='z')
plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img2.png" alt=""/></figure>
<p>Great, I found the above plot by playing around with different z-functions and think it looks pretty cool! Z-functions containing <code>np.log()</code>, <code>np.exp()</code>, <code>np.sin()</code>, <code>np.cos()</code> and combinations of <code>x</code> and <code>y</code> usually lead to interesting plots – I encourage you to experiment yourself.</p>
<p>Now I’ll create 3 different z-functions with the same <code>X</code> and <code>Y</code> as before and create a subplot of them so you can see the differences. </p>
<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=""># Set up Figure and Axes
fig, axes = plt.subplots(1, 3, subplot_kw=dict(projection='3d'), figsize=plt.figaspect(1/3)) # Create 3 z-functions
def z_1(x, y): return np.exp(np.cos(x)*y)
def z_2(x, y): return np.log(x**2 + y**4)
def z_3(x, y): return np.sin(x * y) # Create 3 Z arrays Z_arrays = [z_1(X, Y), z_2(X, Y), z_3(X, Y)]
# Titles for the plots
z_func_names = ['np.exp(np.cos(x)*y)', 'np.log(x**2 + y**4)', 'np.sin(x * y)'] # Plot all 3 wireframes
for Z_array, z_name, ax in zip(Z_arrays, z_func_names, axes): ax.plot_wireframe(X, Y, Z_array) ax.set(title=z_name)
plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img3.png" alt=""/></figure>
<p>I think all of these images demonstrate the power of 3D plotting, and I hope they have encouraged you to create your own.</p>
<p>Now you know how to create any surface or wireframe plot with your data. But so far, you have only used the default settings. Let’s modify them using the available keyword arguments.</p>
<h2>Matplotlib 3D Plot Wireframe</h2>
<p>To make a wireframe plot, call <code>ax.plot_wireframe(X, Y, Z)</code>. These plots give you an overview of the surface. Plus, you can see through them to more easily identify peaks and troughs that may otherwise be hidden.</p>
<p>A wireframe plot works by only plotting a sample of the data passed to it. You can modify how large the samples are with 4 keyword arguments:</p>
<ol>
<li><code>rstride</code> and <code>cstride</code>, or</li>
<li><code>rcount</code> and <code>ccount</code></li>
</ol>
<p>The <code>r</code> and <code>c</code> stand for <code>row</code> and <code>column</code> respectively. The difference between them is similar to the difference between <a href="https://blog.finxter.com/numpy-arange/"><code>np.arange()</code></a> and <a href="https://blog.finxter.com/np-linspace/"><code>np.linspace()</code></a>.</p>
<p>The <code>stride</code> arguments default to 1 and set the step sizes between each sampled point. A stride of 1 means that every value is chosen, and a stride of 10 means that every 10th value is chosen. In this way, it is similar to <code>np.arange()</code> where you select the step size. A larger stride means fewer values are chosen, so your plot renders faster and is less detailed.</p>
<p>The <code>count</code> arguments default to 50 and set the number of (equally spaced) rows/columns sampled. A count of 1 means you use 1 row/column, and a count of 100 means you use 100. In this way, it is similar to <code>np.linspace()</code> where you select the total number of values with the <code>num</code> keyword argument. A larger count means more values are chosen, so your plot renders slower and is more detailed.</p>
<p>The <a href="https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots">matplotlib docs</a> say that you should use the <code>count</code> arguments. However, both are still available, and it doesn’t look like the <code>stride</code> arguments will be depreciated any time soon. Note, though, that you cannot use both <code>count</code> and <code>stride</code>, and if you try to do so, it’s a <code>ValueError</code>.</p>
<p>By setting any of the keyword arguments to 0, you do not sample data along that axis. The result is then a 3D line plot rather than a wireframe.</p>
<p>To demonstrate the differences between different counts or strides, I’ll create a <a href="https://blog.finxter.com/matplotlib-subplots/">subplot</a> with the same <code>X</code>, <code>Y</code> and <code>Z</code> arrays as the first example but with different <code>stride</code> and <code>count</code> values. </p>
<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="">fig, axes = plt.subplots(nrows=1, ncols=3, subplot_kw=dict(projection='3d'), figsize=plt.figaspect(1/3))
# Same as first example
x = np.linspace(-5, 5, num=100)
y = np.linspace(-2, 2, num=70)
X, Y = np.meshgrid(x, y) def z_func(x, y): return np.sin(np.cos(x) + y)
Z = z_func(X, Y) # Define different strides
strides = [1, 5, 10] for stride, ax in zip(strides, axes.flat): ax.plot_wireframe(X, Y, Z, rstride=stride, cstride=stride) ax.set(title=f'stride={stride}') plt.show() </pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img4.png" alt=""/></figure>
<p>Here you can see that a larger stride produces a less detailed wireframe plot. Note that <code>stride=1</code> is the default and is incredibly detailed for a plot that is supposed to give a general overview of the data. </p>
<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="">fig, axes = plt.subplots(nrows=1, ncols=3, subplot_kw=dict(projection='3d'), figsize=plt.figaspect(1/3)) counts = [5, 20, 50] for count, ax in zip(counts, axes.flat): # Use same data as the above plots ax.plot_wireframe(X, Y, Z, rcount=count, ccount=count) ax.set(title=f'count={count}') plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img5.png" alt=""/></figure>
<p>Here you can see that a larger count produces a more detailed wireframe plot. Again note that the default <code>count=50</code> produces a very detailed plot.</p>
<p>Other keyword arguments are passed to <a href="https://matplotlib.org/api/collections_api.html#matplotlib.collections.LineCollection">LineCollection</a>. So you can also change the <a href="https://blog.finxter.com/matplotlib-line-plot/#Matplotlib_Line_Plot_Color"><code>color</code> (<code>c</code>)</a> and <a href="https://blog.finxter.com/matplotlib-line-plot/#Matplotlib_Linestyle"><code>linestyle</code> (<code>ls</code>)</a> amongst other things.</p>
<h2>Matplotlib 3D Plot Surface</h2>
<p>To make a surface plot call <code>ax.plot_surface(X, Y, Z)</code>. Surface plots are the same as wireframe plots, except that spaces in between the lines are colored. Plus, there are some additional keyword arguments you can use, which can add a ton of value to the plot.</p>
<p>First, let’s make the same plots as above with the default surface plot settings and different <code>rcount</code> and <code>ccount</code> values. </p>
<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="">fig, axes = plt.subplots(nrows=1, ncols=3, subplot_kw=dict(projection='3d'), figsize=plt.figaspect(1/3)) counts = [5, 20, 50] for count, ax in zip(counts, axes.flat): # Use same data as the above plots surf = ax.plot_surface(X, Y, Z, rcount=count, ccount=count) ax.set(title=f'count={count}') plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img6.png" alt=""/></figure>
<p>In contrast to wireframe plots, the space in between each line is filled with the color blue. Note that the plots get whiter as the <code>count</code> gets larger. This is because the lines are white, and, as the count increases, there are more lines on each plot. You can modify this by setting the <code>linewidth</code> or <code>lw</code> argument to a smaller number such, as 0.1 or even 0.</p>
<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="">fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, linewidth=0) ax.set(title="linewidth=0")
plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img7.png" alt=""/></figure>
<p>Much nicer! Now you can see the color of the plot rather than the color of the lines. It is possible to almost completely remove the lines by setting <code>antialiased=False</code>.</p>
<p>Antialiasing removes noise from data and smooths out images. By turning it off, the surface is less smooth, and so you can’t see the lines as easily. </p>
<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="">fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False) ax.set(title="linewidth=0, antialiased=False")
plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img8.png" alt=""/></figure>
<p>Now the surface is slightly less smooth, and so you can’t see the lines.</p>
<h2>Maptlotlib 3D Surface Plot Cmap</h2>
<p>Arguably the most crucial keyword argument for surface plots is <code>cmap</code> which sets the colormap. When you look at a surface plot from different angles, having a colormap helps you understand which parts of the surface are where. Usually, you want high points to be one color (e.g., orange) and low points to be another (e.g., black). Having two distinct colors is especially helpful if you look at a plot from different angles (which I will show you how to do in a moment).</p>
<p>There are loads of <a href="https://matplotlib.org/3.2.1/tutorials/colors/colormaps.html">colormaps in matplotlib</a>, and you can see several used in my article on the <a href="https://blog.finxter.com/matplotlib-imshow/#Matplotlib_Imshow_Colormap">matplotlib imshow</a> function.</p>
<p>Now I’ll plot the same data as above but set the colormap to <code>copper</code>.</p>
<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="">fig = plt.figure()
ax = plt.axes(projection='3d') ax.plot_surface(X, Y, Z, lw=0, cmap='copper')
plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img9.png" alt=""/></figure>
<p>The colormap <code>copper</code> maps large z-values to orange and smaller ones to black.</p>
<p>Now I’ll use 3 different and commonly used colormaps for the same plot to give you an idea of how color can help and (massively) hinder your plots. </p>
<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="">fig, axes = plt.subplots(nrows=1, ncols=3, subplot_kw=dict(projection='3d'), figsize=plt.figaspect(1/3)) cmaps = ['copper', 'coolwarm', 'jet'] for cmap, ax in zip(cmaps, axes): ax.plot_surface(X, Y, Z, lw=0, cmap=cmap) ax.set(title=f'{cmap}')
plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img10.png" alt=""/></figure>
<p>The <code>coolwarm</code> colormap works well if you want to highlight extremely high and extremely low points. This <a href="https://cfwebprod.sandia.gov/cfdocs/CompResearch/docs/ColorMapsExpanded.pdf">non-technical paper</a> defines a colormap similar to <code>coolwarm</code> and argues it should be the default cmap for all data science work.</p>
<p>The <code>jet</code> colormap is well known and is a terrible choice for all of your plotting needs. It contains so many colors that it is hard for a human to know which corresponds to high, low, or middle points. I included it as an example here but urge you to <em>never</em> use it in any of your plots.</p>
<p>Now let’s look at how the <code>count</code> and <code>stride</code> arguments can affect the color of your surface plots. For brevity, I will just make one subplot demonstrating different <code>rccount</code> and <code>ccount</code> sizes and leave the reader to experiment with <code>rstride</code> and <code>cstride</code>. </p>
<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="">fig, axes = plt.subplots(nrows=1, ncols=3, subplot_kw=dict(projection='3d'), figsize=plt.figaspect(1/3)) counts = [5, 20, 50] for count, ax in zip(counts, axes.flat): # Use same data as the above plots ax.plot_surface(X, Y, Z, rcount=count, ccount=count, cmap='copper', lw=0) ax.set(title=f'count={count}')
plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img11.png" alt=""/></figure>
<p>If you pass a lower value to the <code>count</code> keyword arguments, there are fewer areas that can be colored. As such, the colors have much more distinct bands when you set the <code>count</code> keyword arguments to smaller values. The change in color is much smoother in the plots that have large <code>count</code> arguments.</p>
<h2>Matplotlib 3D Plot Colorbar</h2>
<p>Adding a colorbar to a 3D surface plot is the same as adding them to other plots.</p>
<p>The simplest method is to save the output of <code>ax.plot_surface()</code> in a variable such as <code>surf</code> and pass that variable to <code>plt.colorbar()</code>.</p>
<p>Here’s an example using the three different colormaps from before.</p>
<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="">fig, axes = plt.subplots(nrows=1, ncols=3, subplot_kw=dict(projection='3d'), figsize=plt.figaspect(1/3)) cmaps = ['copper', 'coolwarm', 'jet'] for cmap, ax in zip(cmaps, axes): # Save surface in a variable: surf surf = ax.plot_surface(X, Y, Z, lw=0, cmap=cmap) # Plot colorbar on the correct Axes: ax fig.colorbar(surf, ax=ax) ax.set(title=f'{cmap}')
plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img12.png" alt=""/></figure>
<p>It’s essential to provide a colorbar for any colored plots you create, especially if you use different colormaps. Remember that <code>colorbar()</code> is a <code>Figure</code> (not <code>Axes</code>) method, and you must use the <code>ax</code> keyword argument to place it on the correct <code>Axes</code>.</p>
<p>Now, let’s see why colormaps are so crucial by rotating the surface plots and viewing them from different angles.</p>
<h2>Matplotlib 3D Plot View_Init</h2>
<p>One way to rotate your plots is by using the magic command <code>%matplotlib notebook</code> at the top of your Jupyter notebooks. If you do this, all your plots appear in interactive windows. If instead, you use <code>%matplotlib inline</code> (the default settings), you have to rotate your plots using code.</p>
<p>Two attributes that control the rotation of a 3D plot: <code>ax.elev</code> and <code>ax.azim</code>, which represent the elevation and azimuthal angles of the plot, respectively.</p>
<p>The elevation is the angle above the XY-plane and the <a href="https://en.wikipedia.org/wiki/Azimuth">azimuth</a> (don’t worry, I hadn’t heard of it before either) is the counter-clockwise rotation about the z-axis. Note that they are properties of the <code>Axes3D</code> object and so you can happily create subplots where each has a different angle.</p>
<p>Let’s find the default values. </p>
<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="">fig = plt.figure()
ax = plt.axes(projection='3d') print(f'The default elevation angle is: {ax.elev}')
print(f'The default azimuth angle is: {ax.azim}')
</pre>
<pre class="wp-block-preformatted">The default elevation angle is: 30
The default azimuth angle is: -60
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img13.png" alt=""/></figure>
<p>You can see that the defaults are 30 and -60 degrees for the elevation and azimuth, respectively.</p>
<p>You can set them to <em>any</em> float you want, and there are two ways to do it:</p>
<ol>
<li>Reassign the <code>ax.azim</code> and <code>ax.elev</code> attributes, or</li>
<li>Use the <code>ax.view_init(elev, azim)</code> method</li>
</ol>
<p>Here’s an example with method 1. </p>
<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=""># Same as usual
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, lw=0, cmap='copper')
# Set axis labels so you know what you are looking at
ax.set(xlabel='x', ylabel='y', zlabel='z') # Reassign rotation angles to 0
ax.azim, ax.elev = 0, 0
plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img14.png" alt=""/></figure>
<p>Here I set both angles to 0, and you can see the y-axis at the front, the x-axis at the side, and the z-axis as vertical.</p>
<p>I’ll now create the same plot using the <code>ax.view_init()</code> method, which accepts two floats: the elevation and azimuth. </p>
<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=""># Same as usual
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, lw=0, cmap='copper')
# Set axis labels so you know what you are looking at
ax.set(xlabel='x', ylabel='y', zlabel='z') # Reassign rotation angles to 0
ax.view_init(elev=0, azim=0)
plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img15.png" alt=""/></figure>
<p>Excellent! This plot looks identical to the one above, but I used the <code>ax.view_init()</code> method instead. If you just want to change one of the angles, only pass one of the keyword arguments.</p>
<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=""># Same as usual
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, lw=0, cmap='copper')
# Set axis labels so you know what you are looking at
ax.set(xlabel='x', ylabel='y', zlabel='z') # Set elevation to 90 degrees
ax.view_init(elev=90)
plt.show()
</pre>
<figure class="wp-block-image"><img src="https://raw.githubusercontent.com/theadammurphy/matplotlib_articles/master/3dplot_advanced/final_html/img/img16.png" alt=""/></figure>
<p>Here I set the elevation to 90 degrees but left the azimuth with its default value. This demonstrates one more reason why colormaps are important: you can infer the shape of the surface from the color (black is low, light is high).</p>
<h2>Conclusion</h2>
<p>Now you know how to create the most critical 3D plots: wireframe and surface plots.</p>
<p>You’ve learned how to create custom 3D plot <a href="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener">datasets </a>using <code>np.linspace()</code>, <code>np.meshgrid()</code> and z-functions. Plus, you can create them with varying degrees of accuracy by modifying the <code>count</code> and <code>stride</code> keyword arguments.</p>
<p>You can make surface plots of any color and colormap and modify them so that the color of the lines doesn’t take over the plot. Finally, you can rotate them by setting the <code>ax.azim</code> or <code>ax.elev</code> attributes to a float of your choice and even use the <code>ax.view_init()</code> method to do the same thing.</p>
<p>Congratulations on mastering these plots! Creating other advanced ones such as contour, tri-surface, and quiver plots for you will be easy. You know all the high-level skills; you just need to go out there and practice.</p>
<h2>Where To Go From Here?</h2>
<p>Do you wish you could be a programmer full-time but don’t know how to start?</p>
<p>Check out the pure value-packed webinar where Chris – creator of Finxter.com – teaches you to become a Python freelancer in 60 days or your money back!</p>
<p><a href="https://tinyurl.com/become-a-python-freelancer">https://tinyurl.com/become-a-python-freelancer</a></p>
<p>It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar.</p>
<p>These are proven, no-BS methods that get you results fast.</p>
<p>This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer, guaranteed.</p>
<p><a href="https://tinyurl.com/become-a-python-freelancer">https://tinyurl.com/become-a-python-freelancer</a></p>
</div>


https://www.sickgaming.net/blog/2020/04/...-advanced/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016