Home > Backend Development > Python Tutorial > Getting started with matplotlib: a quick tutorial

Getting started with matplotlib: a quick tutorial

WBOY
Release: 2024-01-09 10:38:11
Original
1371 people have browsed it

Getting started with matplotlib: a quick tutorial

Get started with matplotlib quickly: a concise tutorial

Matplotlib is a well-known Python data visualization library that provides a wealth of drawing tools and is widely used in data analysis, scientific computing, Engineering drawing and other fields. This article will introduce how to quickly get started with matplotlib and provide some specific code examples.

1. Install Matplotlib
Before we begin, we first need to install the Matplotlib library. It can be installed through the pip command:

pip install matplotlib
Copy after login

2. Basic drawing functions
2.1 Line chart
Line chart is the most commonly used data visualization method, which can show the trend changes of data.

The following is a simple example showing the annual rainfall in a certain place:

import matplotlib.pyplot as plt

years = [2015, 2016, 2017, 2018, 2019, 2020]
rainfall = [800, 900, 850, 1000, 950, 1100]

plt.plot(years, rainfall, marker='o', linestyle='--', color='blue')
plt.xlabel('Year')
plt.ylabel('Rainfall (mm)')
plt.title('Annual Rainfall')
plt.show()
Copy after login

In this example, we first define two lists years and rainfall, representing the year and rainfall respectively. Annual rainfall. Then the line chart is drawn through the plt.plot() function, and the style and color of the line are specified. Finally, the horizontal and vertical axis labels and the title of the chart are set through the plt.xlabel(), plt.ylabel() and plt.title() functions, and the chart is displayed through the plt.show() function.

2.2 Scatter plot
Scatter plot can be used to represent the relationship between two variables and observe the distribution pattern between them.

The following is a simple example showing the relationship between a student's weight and height:

import matplotlib.pyplot as plt

weight = [50, 55, 60, 65, 70, 75]
height = [150, 160, 165, 170, 175, 180]

plt.scatter(weight, height, marker='o', color='red')
plt.xlabel('Weight (kg)')
plt.ylabel('Height (cm)')
plt.title('Student Weight vs Height')
plt.show()
Copy after login

In this example, we define two lists weight and height, representing students respectively weight and height. Then the scatter plot is drawn through the plt.scatter() function, and the style and color of the scatter points are specified. Finally, the horizontal and vertical axis labels and the title of the chart are set through the plt.xlabel(), plt.ylabel() and plt.title() functions, and the chart is displayed through the plt.show() function.

2.3 Histogram
Histogram can be used to compare the size of data between different categories.

The following is a simple example showing the monthly rainfall in a certain place:

import matplotlib.pyplot as plt

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
rainfall = [50, 45, 60, 70, 65, 80]

plt.bar(months, rainfall, color='green')
plt.xlabel('Month')
plt.ylabel('Rainfall (mm)')
plt.title('Monthly Rainfall')
plt.show()
Copy after login

In this example, we define two lists months and rainfall, representing the month and rain respectively. Monthly rainfall. Then the histogram is drawn through the plt.bar() function, and the color of the column is specified. Finally, the horizontal and vertical axis labels and the title of the chart are set through the plt.xlabel(), plt.ylabel() and plt.title() functions, and the chart is displayed through the plt.show() function.

3. Advanced functions
In addition to basic drawing functions, Matplotlib also provides many advanced functions, such as subgraphs, legends, annotations, etc.

3.1 Subplot
You can use the plt.subplot() function to create subplots and draw different charts in each subplot.

The following is a simple example showing two subplots, a line chart and a scatter chart:

import matplotlib.pyplot as plt

years = [2015, 2016, 2017, 2018, 2019, 2020]
rainfall = [800, 900, 850, 1000, 950, 1100]
weight = [50, 55, 60, 65, 70, 75]
height = [150, 160, 165, 170, 175, 180]

plt.subplot(1, 2, 1)
plt.plot(years, rainfall, marker='o', linestyle='--', color='blue')
plt.xlabel('Year')
plt.ylabel('Rainfall (mm)')
plt.title('Annual Rainfall')

plt.subplot(1, 2, 2)
plt.scatter(weight, height, marker='o', color='red')
plt.xlabel('Weight (kg)')
plt.ylabel('Height (cm)')
plt.title('Student Weight vs Height')

plt.tight_layout()
plt.show()
Copy after login

In this example, we use plt.subplot(1, 2, 1) and plt.subplot(1, 2, 2) respectively create two subplots, where (1, 2, 1) represents the first subplot in the subplot with 1 row and 2 columns, (1, 2, 2 ) represents the second subgraph in a subgraph of 1 row and 2 columns. A different graph was then drawn in each subfigure. Finally, adjust the layout of the subgraph through the plt.tight_layout() function, and display the chart through the plt.show() function.

3.2 Legend
You can use the plt.legend() function to add a legend to illustrate the meaning of different data.

The following is a simple example that shows the annual and monthly rainfall in a certain place, and adds the corresponding legend:

import matplotlib.pyplot as plt

years = [2015, 2016, 2017, 2018, 2019, 2020]
rainfall_year = [800, 900, 850, 1000, 950, 1100]
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
rainfall_month = [50, 45, 60, 70, 65, 80]

plt.plot(years, rainfall_year, marker='o', linestyle='--', color='blue', label='Yearly')
plt.bar(months, rainfall_month, color='green', label='Monthly')
plt.xlabel('Time')
plt.ylabel('Rainfall (mm)')
plt.title('Rainfall')
plt.legend()
plt.show()
Copy after login

In this example, we pass in plt. Add the label parameter to the plot() and plt.bar() functions to specify the labels corresponding to annual and monthly rainfall respectively, and then use the plt.legend() function to add a legend. Finally, the horizontal and vertical axis labels and the title of the chart are set through the plt.xlabel(), plt.ylabel() and plt.title() functions, and the chart is displayed through the plt.show() function.

3.3 Annotation
You can use the plt.annotate() function to add text annotations to the chart.

The following is a simple example that shows the maximum annual rainfall in a certain place and adds corresponding text annotations to the chart:

import matplotlib.pyplot as plt

years = [2015, 2016, 2017, 2018, 2019, 2020]
rainfall = [800, 900, 850, 1000, 950, 1100]

plt.plot(years, rainfall, marker='o', linestyle='--', color='blue')
plt.xlabel('Year')
plt.ylabel('Rainfall (mm)')
plt.title('Annual Rainfall')

max_rainfall = max(rainfall)
max_index = rainfall.index(max_rainfall)
plt.annotate(f'Max: {max_rainfall}', xy=(years[max_index], max_rainfall),
             xytext=(years[max_index]+1, max_rainfall-50),
             arrowprops=dict(facecolor='black', arrowstyle='->'))

plt.show()
Copy after login

In this example, we first pass The max() function finds the maximum value of rainfall and the corresponding index, and then uses the plt.annotate() function to add text labels to the chart, specifying the label position and arrow style. Finally, the horizontal and vertical axis labels and the title of the chart are set through the plt.xlabel(), plt.ylabel() and plt.title() functions, and the chart is displayed through the plt.show() function.

4. Summary
Through the introduction of this article, we can see that Matplotlib is a powerful data visualization library that provides a wealth of drawing tools. Whether it is a line chart, a scatter chart or a bar chart, Matplotlib can easily implement it. In addition, Matplotlib also provides some advanced functions, such as subgraphs, legends, labels, etc., which can customize charts more flexibly. I hope this tutorial can help you get started with Matplotlib quickly, and through specific code examples, you can better understand how to use Matplotlib.

The above is the detailed content of Getting started with matplotlib: a quick tutorial. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template