avatarBen Hui

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2261

Abstract

ha=<span class="hljs-number">0.5</span>, marker=<span class="hljs-string">'o'</span>)

ax.set_xlabel(<span class="hljs-string">'X'</span>) ax.set_ylabel(<span class="hljs-string">'Y'</span>) ax.set_zlabel(<span class="hljs-string">'Z'</span>)

plt.show()</pre></div><figure id="9547"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*_SWCvZnvrIGPsVOLeZu7HQ.png"><figcaption></figcaption></figure><p id="220b">It is possible to produce a dynamical plot:</p><div id="0d4d"><pre><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np <span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt <span class="hljs-keyword">from</span> matplotlib.animation <span class="hljs-keyword">import</span> FuncAnimation <span class="hljs-keyword">from</span> IPython.display <span class="hljs-keyword">import</span> HTML

fig = plt.figure() ax = fig.add_subplot(<span class="hljs-number">111</span>, projection=<span class="hljs-string">'3d'</span>)

N = <span class="hljs-number">100</span> xs = np.random.randn(N) ys = np.random.randn(N) zs = np.random.randn(N)

scatter = ax.scatter(xs, ys, zs, c=<span class="hljs-string">'b'</span>, marker=<span class="hljs-string">'o'</span>)

<span class="hljs-keyword">def</span> <span class="hljs-title function_">update</span>(<span class="hljs-params">frame</span>): <span class="hljs-comment"># Change the data randomly</span> xs_new = np.random.randn(N) ys_new = np.random.randn(N) zs_new = np.random.randn(N)

<span class="hljs-comment"># Update the plot</span>
scatter._offsets3d = (xs_new, ys_new, zs_new)

<span class="hljs-keyword">return</span> scatter,

<span class="hljs-comment"># Create an animation</span> animation = FuncAnimation(fig, update, frames=<span class="hljs-built_in">range</span>(<span class="hljs-number">50</span>), interval=<span class="hljs-number">200</span>, blit=<span class="hljs-literal">True</span>)

<span class="hljs-comment"># Display the animation in Jupyter Notebook</span> HTML(animation.to_jshtml())</pre></div><figure id="1dd6"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*IHV1oFGWPLR0LjeHe96zgw.png"><figcaption></figcaption></figure><p id="1f1

Options

c">You can click the PLAY button to see it’s change.</p><p id="b049">The last one, I would like to introduce an interactive plot:</p><div id="eed2"><pre><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np <span class="hljs-keyword">import</span> plotly.graph_objects <span class="hljs-keyword">as</span> go <span class="hljs-keyword">from</span> plotly.subplots <span class="hljs-keyword">import</span> make_subplots

np.random.seed(<span class="hljs-number">0</span>) x = np.random.randn(<span class="hljs-number">100</span>) y = np.random.randn(<span class="hljs-number">100</span>) z = np.random.randn(<span class="hljs-number">100</span>)

fig = make_subplots(rows=<span class="hljs-number">1</span>, cols=<span class="hljs-number">1</span>, specs=[[{<span class="hljs-string">'type'</span>: <span class="hljs-string">'scatter3d'</span>}]])

scatter = go.Scatter3d( x=x, y=y, z=z, mode=<span class="hljs-string">'markers'</span>, marker=<span class="hljs-built_in">dict</span>( size=<span class="hljs-number">5</span>, color=z, colorscale=<span class="hljs-string">'Viridis'</span>, opacity=<span class="hljs-number">0.8</span> ) )

fig.add_trace(scatter)

fig.update_layout( scene=<span class="hljs-built_in">dict</span>( xaxis=<span class="hljs-built_in">dict</span>(title=<span class="hljs-string">'X'</span>), yaxis=<span class="hljs-built_in">dict</span>(title=<span class="hljs-string">'Y'</span>), zaxis=<span class="hljs-built_in">dict</span>(title=<span class="hljs-string">'Z'</span>), ), title=<span class="hljs-string">'Interactive Scatter Plot'</span>, )

fig.show()</pre></div><figure id="4d96"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*UB0dRcnoDXrOptGpnmFmKg.png"><figcaption></figcaption></figure><p id="0b89">Now you can hover your mouse to see every point’s position. You can drag and move the plot and use your mouse wheel to zoom in or out.</p><p id="a850">It uses plotly to draw the scatter plot instead of matplotlib. The syntaxs are similar. But plotly is able to produce interactive plots which is the limit of matplotlib.</p><p id="f435">Thank you for reading.</p></article></body>

How to draw 3D scatter plots in Python?

A scatter plot is commonly used in data science. It can help compare 2 attributes and display their relationship. What if compare 3?

In this article, I am going to introduce how to draw 3D scatter plots and making some extensions.

Let’s see a simple example:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(261)
x = np.random.normal(size=150)
y = np.random.normal(size=150)
z = np.random.normal(size=150)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()

The method is the same as 2D scatter plots. It just adds one more dimension in scatter() function.

Also, it is the same to set up some parameters:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(261)
x = np.random.normal(size=150)
y = np.random.normal(size=150)
z = np.random.normal(size=150)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Set points color, size, transparency and marker type
ax.scatter(x, y, z, c='r', s=10, alpha=0.5, marker='o')

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()

It is possible to produce a dynamical plot:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython.display import HTML

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

N = 100
xs = np.random.randn(N)
ys = np.random.randn(N)
zs = np.random.randn(N)

scatter = ax.scatter(xs, ys, zs, c='b', marker='o')

def update(frame):
    # Change the data randomly
    xs_new = np.random.randn(N)
    ys_new = np.random.randn(N)
    zs_new = np.random.randn(N)
    
    # Update the plot
    scatter._offsets3d = (xs_new, ys_new, zs_new)

    return scatter,

# Create an animation
animation = FuncAnimation(fig, update, frames=range(50), interval=200, blit=True)

# Display the animation in Jupyter Notebook
HTML(animation.to_jshtml())

You can click the PLAY button to see it’s change.

The last one, I would like to introduce an interactive plot:

import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots

np.random.seed(0)
x = np.random.randn(100)
y = np.random.randn(100)
z = np.random.randn(100)

fig = make_subplots(rows=1, cols=1, specs=[[{'type': 'scatter3d'}]])

scatter = go.Scatter3d(
    x=x,
    y=y,
    z=z,
    mode='markers',
    marker=dict(
        size=5,
        color=z,
        colorscale='Viridis',
        opacity=0.8
    )
)

fig.add_trace(scatter)

fig.update_layout(
    scene=dict(
        xaxis=dict(title='X'),
        yaxis=dict(title='Y'),
        zaxis=dict(title='Z'),
    ),
    title='Interactive Scatter Plot',
)

fig.show()

Now you can hover your mouse to see every point’s position. You can drag and move the plot and use your mouse wheel to zoom in or out.

It uses plotly to draw the scatter plot instead of matplotlib. The syntaxs are similar. But plotly is able to produce interactive plots which is the limit of matplotlib.

Thank you for reading.

Python
Data Science
Data Analysis
Data
Data Visualization
Recommended from ReadMedium