[파이썬] matplotlib 선 그래프 그리기

Matplotlib is a popular data visualization library in Python that allows you to create a variety of charts and plots. One of the most commonly used types of plots is the line plot or 선 그래프 in Korean. In this blog post, we will explore how to create line plots using Matplotlib in Python.

Let’s start by installing the necessary packages. Open your command prompt or terminal and run the following command:

pip install matplotlib

Once the installation is complete, you’re ready to get started.

Importing the Library

First, import the necessary libraries. In this case, we’ll need matplotlib.pyplot, which is a collection of functions that enable us to create various types of plots.

import matplotlib.pyplot as plt

Creating the Line Plot

To create a line plot, you need two sets of data - one representing the x-axis values and the other representing the y-axis values. In the example below, we’ll create a simple line plot to show the trend of monthly sales over a year.

# Monthly sales data
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
sales = [35000, 42000, 38000, 41000, 48000, 52000, 51000, 49000, 47000, 52000, 55000, 60000]

# Plotting the data
plt.plot(months, sales)

# Adding labels and title
plt.xlabel('Months')
plt.ylabel('Sales')
plt.title('Monthly Sales Trend')

# Displaying the plot
plt.show()

Customizing the Plot

You can further customize the line plot by adding grid lines, changing the line style, or adding markers to data points. Here’s an example of customizing the line plot by adding grid lines and changing the line style:

# Plotting the data with customizations
plt.plot(months, sales, marker='o', linestyle='-', color='b')
plt.grid(True)

# Adding labels and title
plt.xlabel('Months')
plt.ylabel('Sales')
plt.title('Monthly Sales Trend')

# Displaying the plot
plt.show()

Conclusion

In this blog post, we learned how to create line plots using Matplotlib in Python. We started by importing the necessary libraries, then created a simple line plot to visualize monthly sales data. We also explored how to customize the plot by adding grid lines and changing the line style.

Line plots are a powerful tool for visualizing trends and patterns in data. With Matplotlib, you have the flexibility to create insightful and visually appealing line plots to communicate your data effectively.