如何在Matplotlib中添加网格线(附代码)

212 阅读2分钟

在这篇文章中,我们将学习如何在Matplotlib绘图中添加网格线。Matplotlib是一个Python绘图库,它为创建科学绘图和图形提供了一个互动环境。让我们直接进入主题。

在Matplotlib图中添加网格线的步骤

现在让我们来看看在Matplotlib图中添加网格线的步骤。

1.安装模块

Matplotlib-

pip install matplotlib

Pyplot-

pyplot子模块包含了Matplotlib的大部分功能

注意:编译器通常不具备显示图形的能力,但在Python中,我们可以通过添加几行代码使其兼容。

import sys
import matplotlib
matplotlib.use('Agg')
# Matplotlib relies on a backend to render the plots and here ‘Agg’ is the default backend

import matplotlib.pyplot as pyt
# lines of code for plotting a graph

pyt.savefig(sys.stdout.buffer)
sys.stdout.flush()
# these two lines are used to avoid excess buffering and print the data without any delay and make sure the code works

例子

import sys
import matplotlib
matplotlib.use('Agg')
# Matplotlib relies on a backend to render the plots and here ‘Agg’ is the default backend

import matplotlib.pyplot as pyt
import numpy as np

x = np.array([0, 10])
y = np.array([0, 200])

pyt.plot(x, y)

pyt.show()

pyt.savefig(sys.stdout.buffer)
sys.stdout.flush()

绘制一个图形

2.在图中添加网格线

我们可以使用Pyplot的**grid()**函数来为一个图添加网格线。

例子

x = np.array([0,10])
y = np.array([0,200])
pyt.title("Sales of Ice Cream")    
# to represent the title on the plot

pyt.xlabel("Days")                      # to label the x-axis
pyt.ylabel("Customers")            # to label the y-axis
pyt.plot(x, y)
pyt.grid()
pyt.show()

绘图

3.指定要显示的网格线

使用grid()函数中的axis参数,我们可以指定显示哪些网格线。允许的值是。'x','y' 或'both'。但是默认值是'both',所以我们可以不写它。

例子:

  • 只显示X轴的网格线
pyt.grid(axis = ‘y’)

只绘制X轴

  • 只显示Y轴的网格线
pyt.grid(axis = ‘x’)

绘制Y轴

4.为网格设置线条属性

我们可以通过各种方式来设置网格的属性,如颜色、样式等。

我们定义样式为:color='specified_color', linestyle='specified_linestyle', linewidth= number, axis='specified_axis('x', 'y' or 'both')'

比如说

pyt.grid(color = 'red', linestyle = '--', linewidth = 0.75, axis='both')

网格属性改变后的图画

总结

本教程到此结束!希望你已经学会了如何在Python中绘制网格线,以及使用matplotlib库绘制网格线的各种属性。请继续关注Ask Python,了解更多此类Python教程。