Data visualization artifact! Matplotlib Python Tutorial | From entry to proficiency in drawing various types of graphics and saving graphics

Hello everyone, I am a fish who loves to eat bear's paws. Today I will bring you an interesting and cheerful Matplotlib Python tutorial. Matplotlib is one of the most popular data visualization libraries in Python, which helps us transform data into easy-to-understand charts and graphs. Whether you are a beginner or a professional, Matplotlib is a very useful tool. let's start!

Part 1: Installing Matplotlib

Before we start, we need to install Matplotlib first. Run the following command in a terminal or command line to install Matplotlib:

pip install matplotlib

If you are using Jupyter Notebook or an interactive notebook like Google Colab, you can install Matplotlib with the following command:

pip install matplotlib

After the installation is complete, we can start using Matplotlib.

Part II: Basics of Matplotlib

Before using Matplotlib, we need to understand some basics. The most commonly used objects in Matplotlib are Figure and Axes objects.

  • The Figure object is a canvas on which we can draw multiple Axes objects.
  • The Axes object is an area that contains a figure and axes. We can plot data on the Axes object.

In Matplotlib, we can use the pyplot submodule to draw graphics. The following are the basic steps to draw a graph:

  1. Create a Figure object.
  2. Create an Axes object.
  3. Plot data on Axes objects.
  4. Display graphics.

Here is a simple example:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
# 创建一个Figure对象
fig = plt.figure()

# 创建一个Axes对象
ax = fig.add_subplot(111)

# 在Axes对象上绘制数据
ax.plot([1, 2, 3, 4], [1, 4, 9, 16])

# 显示图形
plt.show()

insert image description here

The above code creates a simple line chart. We plotted the data on the Axes object using the plot() function and displayed the graph using the show() function.

Part III: Drawing Different Types of Graphs

In Matplotlib, we can draw many types of graphics, including line graphs, histograms, scatterplots, pie charts, and more. Next, we'll cover how to draw different types of graphs.

line chart

A line graph is a common data visualization used to show how data changes over time or other variables. In Matplotlib, we can use the plot() function to draw a line graph.

Here is a simple example:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
# 创建一个Figure对象
fig = plt.figure()

# 创建一个Axes对象
ax = fig.add_subplot(111)

# 在Axes对象上绘制折线图
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
ax.plot(x, y)

# 添加标题和标签 
ax.set_title("折线图") 
ax.set_xlabel("X轴") 
ax.set_ylabel("Y轴")
# 显示图形
plt.show()

insert image description here

The above code creates a simple line chart. We have drawn polylines on the Axes object using the plot() function and added titles and labels using the set_title(), set_xlabel() and set_ylabel() functions.

histogram

Histograms are used to compare data across multiple projects. In Matplotlib, we can use the bar() function to draw a histogram.

Here is a simple example:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
# 创建一个Figure对象
fig = plt.figure()

# 创建一个Axes对象
ax = fig.add_subplot(111)

# 在Axes对象上绘制柱状图
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
ax.bar(x, y)

# 添加标题和标签
ax.set_title("柱状图")
ax.set_xlabel("X轴")
ax.set_ylabel("Y轴")

# 显示图形
plt.show()

insert image description here

The above code creates a simple histogram. We drew a bar chart on the Axes object using the bar() function and added a title and label using the set_title(), set_xlabel() and set_ylabel() functions.

Scatterplot

Scatterplots are used to show the relationship between two variables. In Matplotlib, we can use the scatter() function to draw a scatterplot.

Here is a simple example:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
# 创建一个Figure对象
fig = plt.figure()

# 创建一个Axes对象
ax = fig.add_subplot(111)

# 在Axes对象上绘制散点图
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
ax.scatter(x, y)

# 添加标题和标签
ax.set_title("散点图")
ax.set_xlabel("X轴")
ax.set_ylabel("Y轴")

# 显示图形
plt.show()

insert image description here

The above code creates a simple scatterplot. We plotted the scatterplot on the Axes object using the scatter() function, and added titles and labels using the set_title(), set_xlabel(), and set_ylabel() functions.

pie chart

Pie charts are used to show the proportions of different categories. In Matplotlib, we can use the pie() function to draw pie charts.

Here is a simple example:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
# 创建一个Figure对象
fig = plt.figure()

# 创建一个Axes对象
ax = fig.add_subplot(111)

# 在Axes对象上绘制饼图
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
ax.pie(sizes, labels=labels)

# 添加标题
ax.set_title("饼图")

# 显示图形
plt.show()

insert image description here

The above code creates a simple pie chart. We have drawn a pie chart on the Axes object using the pie() function and added a title using the set_title() function.

Part IV: Advanced Features of Matplotlib

In addition to basic plotting functions, Matplotlib also provides many advanced functions that can help us better control the style and layout of graphics. Next, we'll cover some of Matplotlib's advanced features.

subgraph

Subplots in Matplotlib are a way of combining multiple figures together for display. In Matplotlib, we can use the subplot() function to create subplots.

Here is a simple example:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
# 创建一个Figure对象
fig = plt.figure()

# 创建一个包含2个子图的GridSpec对象
gs = fig.add_gridspec(1, 2)

# 创建第一个子图
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot([1, 2, 3], [1, 2, 3])
ax1.set_title("子图1")

# 创建第二个子图
ax2 = fig.add_subplot(gs[0, 1])
ax2.plot([1, 2, 3], [3, 2, 1])
ax2.set_title("子图2")

# 显示图形
plt.show()

insert image description here

The above code creates a figure with 2 subplots. We created a GridSpec object with 1 row and 2 columns using the add_gridspec() function, and created two subplots on the GridSpec object using the add_subplot() function. When setting the subplot's title, we use the set_title() function.

legend

Legends in Matplotlib are used to explain the meaning of the different elements in a graph. In Matplotlib, we can use the legend() function to add a legend.

Here is a simple example:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
# 创建一个Figure对象
fig = plt.figure()

# 创建一个Axes对象
ax = fig.add_subplot(111)

# 在Axes对象上绘制折线图
x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [1, 2, 3, 4]
ax.plot(x, y1, label='数据集1')
ax.plot(x, y2, label='数据集2')

# 添加图例
ax.legend()

# 添加标题和标签
ax.set_title("折线图")
ax.set_xlabel("X轴")
ax.set_ylabel("Y轴")

# 显示图形
plt.show()

insert image description here

The above code creates a line chart with a legend. When drawing a line chart, we use the label parameter to specify the name of each data set, and use the legend() function when adding a legend. When setting the title and label of the figure, we used the set_title(), set_xlabel() and set_ylabel() functions.

note

In Matplotlib, we can add annotations to a figure using the annotate() function. Annotations can be used to explain some particular points or areas in a drawing.

Here is a simple example:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
# 创建一个Figure对象
fig = plt.figure()

# 创建一个Axes对象
ax = fig.add_subplot(111)

# 在Axes对象上绘制折线图
x = [1, 2, 3, 4]
y = [1, 4, 9, 16] 
ax.plot(x, y)

# 添加注释

ax.annotate('最大值', xy=(3, 9), xytext=(2, 12), arrowprops=dict(facecolor='red', shrink=0.05))

# 添加标题和标签

ax.set_title("折线图") 
ax.set_xlabel("X轴") 
ax.set_ylabel("Y轴")

# 显示图形

plt.show()

insert image description here

The above code creates a line chart with annotations. We add annotations to the graph using the annotate() function, specifying the location of the annotation text and the properties of the arrow. When setting the title and label of the figure, we used the set_title(), set_xlabel() and set_ylabel() functions.

save graph

In Matplotlib, we can save a figure as a file using the savefig() function. Matplotlib supports a variety of file formats, including PNG, PDF, SVG, and EPS, among others.

Here is a simple example:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
# 创建一个Figure对象
fig = plt.figure()

# 创建一个Axes对象
ax = fig.add_subplot(111)

# 在Axes对象上绘制折线图
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
ax.plot(x, y)

# 添加标题和标签
ax.set_title("折线图")
ax.set_xlabel("X轴")
ax.set_ylabel("Y轴")

# 保存图形
plt.savefig('line_chart.png')

# 显示图形
plt.show()

insert image description here

The above code saves the drawn line chart as a file in PNG format. When we call the savefig() function, we specify the name and format of the saved file.

conclusion of issue

error 1

problem error code

C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm_matplotlib_backend\backend_interagg.py:68: UserWarning: Glyph 36724 (\N{
    
    CJK UNIFIED IDEOGRAPH-8F74}) missing from current font.
  FigureCanvasAgg.draw(self)
C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm_matplotlib_backend\backend_interagg.py:68: UserWarning: Glyph 25240 (\N{
    
    CJK UNIFIED IDEOGRAPH-6298}) missing from current font.
  FigureCanvasAgg.draw(self)
C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm_matplotlib_backend\backend_interagg.py:68: UserWarning: Glyph 32447 (\N{
    
    CJK UNIFIED IDEOGRAPH-7EBF}) missing from current font.
  FigureCanvasAgg.draw(self)
C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm_matplotlib_backend\backend_interagg.py:68: UserWarning: Glyph 22270 (\N{
    
    CJK UNIFIED IDEOGRAPH-56FE}) missing from current font.
  FigureCanvasAgg.draw(self)

problem causes

These warnings are due to missing fonts for the corresponding glyphs. These glyphs are CJK (Chinese, Japanese, Korean) Unified Ideographs (Chinese characters and other East Asian pictographs in Unicode). If you need to use these glyphs in Matplotlib charts, you can try to install fonts that contain them, such as SimSun, SimHei, STSong and other Chinese fonts.

solution

In Matplotlib, you can use the rcParams parameter to set the font globally, or set the font individually for each plot. For example, you can use the following code to set the global font to SimHei:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'

Or when drawing a chart, use the following code to set the font:

import matplotlib.pyplot as plt
plt.plot(x, y)
plt.xlabel('横轴', fontproperties='SimHei')
plt.ylabel('纵轴', fontproperties='SimHei')
plt.show()

In this way, you can use the SimHei font to draw charts, and those errors will not appear.

If you have other questions, you can private message me, and I will reply when I see it.

If my blog is helpful to you, please thank you three times.

Guess you like

Origin blog.csdn.net/godnightshao/article/details/130278001