[파이썬] Matplotlib 그래프 조합

Matplotlib is a popular data visualization library in Python that allows you to create various types of graphs and plots. One of the powerful features of Matplotlib is its ability to combine multiple graphs into a single figure. In this blog post, we will explore how to create combined graphs using Matplotlib.

Getting Started

Before we start, make sure you have Matplotlib installed. You can install it using pip:

pip install matplotlib

Once you have Matplotlib installed, you can import it in your Python script or Jupyter notebook:

import matplotlib.pyplot as plt

Combining Graphs

To combine multiple graphs in Matplotlib, we can make use of the subplot() function. This function allows us to divide the figure into several subplots and specify the position of each subplot.

Here’s an example of combining two line graphs into a single figure with two subplots:

import matplotlib.pyplot as plt
import numpy as np

# Generate some random data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Create a figure with two subplots
plt.subplot(2, 1, 1)  # First subplot
plt.plot(x, y1, 'r')
plt.title('Sin(x)')

plt.subplot(2, 1, 2)  # Second subplot
plt.plot(x, y2, 'b')
plt.title('Cos(x)')

# Adjust spacing between subplots
plt.subplots_adjust(hspace=0.5)

# Show the combined graphs
plt.show()

In the above example, the subplot() function is used to create a figure with two subplots stacked vertically. The subplot() function takes three arguments: the number of rows, the number of columns, and the index of the currently active subplot.

We then plot the first line graph on the first subplot using plt.subplot(2, 1, 1) and plot the second line graph on the second subplot using plt.subplot(2, 1, 2).

Finally, we adjust the spacing between subplots using plt.subplots_adjust() and display the combined graphs using plt.show().

Conclusion

Combining graphs in Matplotlib allows you to present multiple visualizations in a single figure, making it easier to compare and analyze data. With the subplot() function, you can create complex layouts and customize the appearance of each subplot.

Explore the official Matplotlib documentation and experiment with different graph combinations to create meaningful visualizations.

Matplotlib is a powerful tool that empowers you to create beautiful and informative graphs for your data analysis and visualization projects.