[파이썬] 3D 그래프 그리기

In this tutorial, we will learn how to create 3D graphs in Python using the popular matplotlib library. Matplotlib is a powerful data visualization library that allows us to create a wide range of graphs and plots, including 3D graphs.

Setting up the Environment

Before we begin, make sure you have Python and matplotlib installed on your machine. You can install matplotlib using the following command:

pip install matplotlib

Once you have installed matplotlib, let’s import the necessary libraries and set up the environment:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Set up the figure and axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

Creating a Simple 3D Plot

To create a simple 3D plot, we need data points in three dimensions. Let’s generate some random data points and plot them:

# Generate random data
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)

# Plot the data points
ax.scatter(x, y, z)

# Set labels for the axes
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

# Display the plot
plt.show()

This code will generate 100 random data points in three dimensions and plot them as a scatter plot. The resulting plot will be displayed with labeled axes.

Creating a 3D Surface Plot

In addition to scatter plots, matplotlib also allows us to create 3D surface plots. Surface plots are useful for visualizing functions of two variables.

Let’s create an example of a 3D surface plot using the plot_surface function:

# Generate data for the surface plot
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Plot the surface
ax.plot_surface(X, Y, Z, cmap='viridis')

# Set labels for the axes
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

# Display the plot
plt.show()

In this code, we generate a grid of x and y values using meshgrid, calculate the corresponding z values using a mathematical function, and then plot the surface.

Conclusion

In this tutorial, we explored how to create 3D graphs using python and matplotlib. We covered creating simple scatter plots and more advanced surface plots. With these techniques, you can visualize your data and gain deeper insights into your data patterns.

Matplotlib provides a wide range of customization options for 3D plots, so feel free to experiment and create stunning visualizations that suit your specific needs. Happy plotting!